尝试从数据帧中查找值,如下所示:

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

10-08 04:15