python - 根据当前列中的值在 Pandas 中的 np.where 上创建条件

标签 python pandas numpy

我在 Pandas 中有一个数据框(下面的子集)。

DATE       IN 200D_MA   TEST    
10/30/2013  0   1        0  
10/31/2013  0   1        0  
11/1/2013   1   1        1  IN & 200D_MA both =1, results 1
11/4/2013   0   1        1  PREVIOUS TEST ROW =1 & 200DM_A = 1, TEST ans=1
11/5/2013   0   1        1  PREVIOUS TEST ROW =1 & 200DM_A = 1, TEST ans=1
11/6/2013   0   1        1  
11/7/2013   0   1        1  
11/8/2013   0   1        1  
11/11/2013  0   0        0  PREVIOUS TEST ROW =1 & 200DM_A = 0, TEST ans=0

这在 excel 中很容易做到,所以我认为在 python 中也很容易做到。我有使用嵌套 np.where 公式的代码

df3['TEST'] = np.where( (df3['IN'] == 1) & (df3['200D_MA'] == 1),1,\
                       np.where( (df3['TEST'].shift(-1) == 1)\
                       & (df3['200D_MA'] == 1),1,0)) 

但它会抛出一个 KeyError: 'IN' > 大概是因为我正在使用尚未创建的列中的条件。谁能帮我弄清楚如何做到这一点?

最佳答案

似乎您需要条件ffill

df['TEST']=df.loc[df.IN==1,'IN']
df.loc[df['200D_MA']==1,'TEST']=df.loc[df['200D_MA']==1,'TEST'].ffill()
df.fillna(0,inplace=True)
df.TEST=df.TEST.astype(int)
df
Out[349]: 
         DATE  IN  200D_MA  TEST
0  10/30/2013   0        1     0
1  10/31/2013   0        1     0
2   11/1/2013   1        1     1
3   11/4/2013   0        1     1
4   11/5/2013   0        1     1
5   11/6/2013   0        1     1
6   11/7/2013   0        1     1
7   11/8/2013   0        1     1
8  11/11/2013   0        0     0

关于python - 根据当前列中的值在 Pandas 中的 np.where 上创建条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181390/

相关文章:

python - string.format() with {} inside string as string

python - 如何将 PATH 变量添加到 Linux 应用服务计划

python - 对不带年、月、日的时间戳数组进行算术

python - 无法在 Mountain Lion 上安装 numpy

python - 跨语言客户端/服务器的双向 RPC 选项

python - 我如何将 abc.abstractproperty 与类方法结合起来制作 "abstract class property"?

python - 我正在尝试将数据框插入本地 MySQL 数据库

python - 将 Simple Imputer 与 Pandas 数据框一起使用?

python - 如果每个值都相等,则删除 pandas 数据框行

python - 使用 numpy 计算成对互信息的最佳方法