python - 如何对当前行与 Pandas 中的上一行和下一行进行迭代比较?

标签 python for-loop pandas

在 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/

相关文章:

python - 如果用户没有响应,则继续脚本

c++ - 在 C++ 中解析 YAML 字典列表

python - Pandas 重新索引具有重复键的数据框

python - 比带条件的 iterrows 更快的方法(每行的前驱和后继)

python-3.x - 将包含集合的数据框列的每一行转换为包含列表的列

python - 如何在 csv 文件中的单个单元格中写入而不是单独的单元格?

python - 使用 "del np.dtype"后,重新导入 numpy 是否应该修复此问题?

python - 根据列表的内容从数据框中选择列

c - 使用 3D 数组 - 无法进行输出

ios - 在 NSArray 2 中搜索 NSArray 1 以获取值匹配元素的最佳方法