【问题标题】:Condition within for loop is ambiguousfor 循环中的条件不明确
【发布时间】:2021-12-21 16:28:47
【问题描述】:

我正在尝试在数据帧上运行条件 for 循环。如果不满足条件,则将最后一行附加到结果数据帧中。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(100, size=(100,3)), columns=['Value1', 'Value2', 'Value3'])

split_df = [df[i:i+12] for i in range(0, len(df))]

result = []
for i in split_df:
    if i == 0:
        result = split_df[i]
    else:
        last_row = split_df[i].tail(1)
        result = result.append(last_row, ignore_index=True)

对于If i == 0:,我收到以下错误:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我该如何解决这个问题?

【问题讨论】:

  • 当您查看i == 0 时,您认为i 是什么?
  • 仅供参考 split_df = [df[i:i+12] for i in range(0, len(df))] 相当于 df.rolling(12)

标签: python pandas dataframe for-loop if-statement


【解决方案1】:

iDataFrame,因为您正在循环遍历DataFrames 的列表。你可能想这样写循环:

for i, df in enumerate(split_df):
    if i == 0:
        result = df
    else:
        last_row = df.tail(1)
        result.append(last_row, ignore_index=True)

还请注意,您不想写 result = result.append(...) - 相反,您只需写 result.append(...) 因为append() 修改了循环就地,它不会返回任何东西。

【讨论】:

  • 谢谢,这解决了这个问题。我没有意识到我必须枚举 df。
猜你喜欢
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2021-05-06
  • 2020-12-26
  • 2019-06-04
  • 1970-01-01
相关资源
最近更新 更多