【问题标题】:Iterate over pandas rows and using shift() in if statement遍历 pandas 行并在 if 语句中使用 shift()
【发布时间】:2022-11-23 22:22:00
【问题描述】:

我正在尝试遍历数据框,然后应用 shift() 函数。它给了我错误:“numpy.int64”对象没有属性“shift”

在保持迭代的同时执行此操作的任何简单方法?它应该只显示最后一个索引值。

import pandas as pd

df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
                  columns=['A', 'B', 'C'])

for index, row in df.iterrows():
  if row['B'].shift(1) >= 4:
    print(index)

【问题讨论】:

  • 你想做什么?您可以将先前的值保存在变量中,但请解释您的目标,因为可能不需要循环

标签: python pandas


【解决方案1】:

循环方法是使用一个变量:

prev = None
for index, row in df.iterrows():
  if prev is not None and prev >= 4:
    print(index)
  prev = row['B']

输出:

2

但是,如果可以,请使用矢量代码:

out = df.index[df['B'].shift().ge(4)]

# if needed to print
print(*out, sep='
')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 2015-10-03
    相关资源
    最近更新 更多