我有一些看起来像3,4,5,-5,4,5,6,3,2,6,6的数据集,我想要创建一个数据集,它总是有0的索引,这些索引匹配dataset 1中的第一个正数序列,还有一个用于保留的索引。
So for a = [3,4,5,-5,4,5,6,3,2-6,6] it should be
b = [0,0,0, 1,1,1,1,1,1,1]如果我用熊猫和蟒蛇,怎么能从a中产生b呢?
发布于 2022-07-29 22:12:39
既然你标记了熊猫,下面是一个使用Series的解决方案
import pandas as pd
s = pd.Series([3, 4, 5, -5, 4, 5, 6, 3, 2 - 6, 6])
# find the first index that is greater than zero
idx = (s > 0).idxmin()
# using the index set all the values before as 0, otherwise 1
res = pd.Series(s.index >= idx, dtype=int)
print(res)输出
0 0
1 0
2 0
3 1
4 1
5 1
6 1
7 1
8 1
9 1
dtype: int64如果你喜欢单线的话:
res = pd.Series(s.index >= (s > 0).idxmin(), dtype=int)发布于 2022-07-30 01:17:31
您可以在布尔序列上使用cummax:
s = pd.Series([3, 4, 5, -5, 4, 5, 6, 3, 2 - 6, 6])
out = s.lt(0).cummax().astype(int)输出:
0 0
1 0
2 0
3 1
4 1
5 1
6 1
7 1
8 1
9 1
dtype: int64如果您确实在处理列表,那么就不需要熊猫了,而且numpy应该更高效:
import numpy as np
a = [3,4,5,-5,4,5,6,3,2-6,6]
b = np.maximum.accumulate(np.array(a)<0).astype(int).tolist()输出:[0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
如果列表很小,则应该首选纯python:
from itertools import accumulate
b = list(accumulate((int(x<0) for x in a), max))输出:[0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
https://stackoverflow.com/questions/73171399
复制相似问题