熊猫:根据条件创建新列

时间:2020-09-20 12:25:56

标签: python

我是熊猫的新手,我进行了一些分析练习。我想创建一个新列,其值是有条件的两列相乘: 通过乘以典型价格*交易量来计算资金流量,如果一天的“典型价格”大于前一天的“典型价格”,则该值为正。否则,该值为负。遵循此规则,第一行将没有“资金流量”值,因为它无法与前一天进行比较

原始数据集如下:

Volume  Typical Price
3509      47.810000
4862      48.406667
1810      49.260000
3824      49.263333
2209      47.386667
4558      45.573333
3832      44.396667
3778      43.750000
1005      44.640000
4047      43.760000
2201      44.383333
2507      45.156667

预期结果是将有新列“现金流量正数”和“负数”。

Volume  Typical Price   Money Flow Positive    Money Flow Negative
3509      47.810000
4862      48.406667
1810      49.260000
3824      49.263333
2209      47.386667
4558      45.573333
3832      44.396667
3778      43.750000
1005      44.640000
4047      43.760000
2201      44.383333
2507      45.156667

我想到的逻辑是...

if Money flow negative than previous Money flow move to Money Flow negative
if Money flow positive than previous Money flow move to Money Flow positive

我不确定如何在具有上述条件的大熊猫中创建if语句,有什么建议吗?

1 个答案:

答案 0 :(得分:2)

看看是否有帮助:

df['Money flow positive']= np.where(df['Typical Price'].shift() < df['Typical Price'],df['Typical Price']*df['Volume'] , '')
df['Money flow negative']= np.where(df['Typical Price'].shift() >= df['Typical Price'],df['Typical Price']*df['Volume'] , '')
df

enter image description here