在 Pandas 中是否有一些聪明的或 Pythonic 的方法来做类似下面的事情?
for index, row in pd.DataFrame().iterrows():
if (row[previous_index]>=row and row[next_index]>=row):
row=(row[previous_index]+row[next_index])/2
最佳答案
下面是如何使用 rolling_apply
为 Series 实现此功能。目前尚不清楚您的比较如何在 DataFrame 中的整个行上进行。
In [5]: s = Series([1,2,3,2,5])
In [6]: def f(rows):
if (rows[0] >= rows[1]) and (rows[2] >= rows[1]):
return (rows[0] + rows[2]) / 2
else:
return rows[1]
...:
In [7]: pd.rolling_apply(s, 3, f, center=True)
Out[7]:
0 NaN
1 2
2 3
3 4
4 NaN
dtype: float64
关于python - 如何对当前行与 Pandas 中的上一行和下一行进行迭代比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25689368/