我正在尝试遍历 pandas 数据框并在满足条件时更新值,但出现错误。
for line, row in enumerate(df.itertuples(), 1):
if row.Qty:
if row.Qty == 1 and row.Price == 10:
row.Buy = 1
AttributeError: can't set attribute
最佳答案
首先在 pandas 中迭代是可能的,但非常慢,因此使用了另一种矢量化解决方案。
我想你可以使用 iterrows
如果你需要迭代:
for idx, row in df.iterrows():
if df.loc[idx,'Qty'] == 1 and df.loc[idx,'Price'] == 10:
df.loc[idx,'Buy'] = 1
但更好的是使用矢量化解决方案——使用 loc
通过 bool 掩码设置值:
mask = (df['Qty'] == 1) & (df['Price'] == 10)
df.loc[mask, 'Buy'] = 1
或使用 mask
的解决方案:
df['Buy'] = df['Buy'].mask(mask, 1)
或者如果你需要 if...else
使用 numpy.where
:
df['Buy'] = np.where(mask, 1, 0)
示例。
按条件设置值:
df = pd.DataFrame({'Buy': [100, 200, 50],
'Qty': [5, 1, 1],
'Name': ['apple', 'pear', 'banana'],
'Price': [1, 10, 10]})
print (df)
Buy Name Price Qty
0 100 apple 1 5
1 200 pear 10 1
2 50 banana 10 1
mask = (df['Qty'] == 1) & (df['Price'] == 10)
df['Buy'] = df['Buy'].mask(mask, 1)
print (df)
Buy Name Price Qty
0 100 apple 1 5
1 1 pear 10 1
2 1 banana 10 1
df['Buy'] = np.where(mask, 1, 0)
print (df)
Buy Name Price Qty
0 0 apple 1 5
1 1 pear 10 1
2 1 banana 10 1
关于python - 遍历 pandas 数据帧并更新值 - AttributeError : can't set attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43222878/