[英]Pandas: series of True or False in a column, select in another column the value when there is a True
[英]For loop Pandas Series, once True print another value
尝试从数据帧中查找值,如下所示:
df = pd.DataFrame({'Price': [2,4,6,7,8],
'compare': [True, True, False, False, True]})
如果“比较”中的值为“真”,则我想在“价格”列中打印同一行中对应的数字,一旦打印,我想在“价格”列中打印前一行,然后“价格”列中的一位
有任何想法吗? 我想到要遍历然后尝试获取这些值,但我找不到实现它的方法。
关于我可以运行并获取这些值的pd方法或函数的任何建议?
IIUC:
In [42]: df.assign(prev_price=df.Price.shift(), next_price=df.Price.shift(-1))
Out[42]:
Price compare next_price prev_price
0 2 True 4.0 NaN
1 4 True 6.0 2.0
2 6 False 7.0 4.0
3 7 False 8.0 6.0
4 8 True NaN 7.0
过滤:
In [43]: df.loc[df.compare].assign(prev_price=df.Price.shift(), next_price=df.Price.shift(-1))
Out[43]:
Price compare next_price prev_price
0 2 True 4.0 NaN
1 4 True 6.0 2.0
4 8 True NaN 7.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.