我正在嘗試在資料幀上運行條件 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().
我該如何解決這個問題?
uj5u.com熱心網友回復:
i是 a DataFrame,因為您正在遍歷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()修改了回圈in-place,并且它不回傳任何內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353846.html
下一篇:部分字串過濾器熊貓
