如何在Pandas中对当前行与前一行和后一行进行迭代比较?

3
有没有一些聪明或Pythonic的方法在Pandas中执行以下操作?
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
2个回答

3

以下是如何使用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

1
我不明白您想在行上执行什么操作,但是shift方法适合您。(既有Series.shift也有DataFrame.shift。)
import pandas as pd
import numpy as np

np.random.seed(1)
ser = pd.Series(np.random.random_integers(0,10,10))

shift_down_by_one = ser.shift(1)
shift_up_by_one = ser.shift(-1)

mask = (shift_up_by_one >= ser) & (shift_down_by_one >= ser)
ser.loc[mask] = (shift_up_by_one + shift_down_by_one) / 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接