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

时间:2014-09-05 15:33:04

标签: python for-loop pandas

是否有一些智能或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 个答案:

答案 0 :(得分:3)

以下是使用rolling_apply为系列实现此功能的方法。目前还不清楚你的比较如何在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 :(得分:1)

我不明白你想对行执行什么操作,但shift方法适合你。 (Series.shiftDataFrame.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