python - 遍历 pandas 数据帧并更新值 - AttributeError : can't set attribute

标签 python pandas dataframe

我正在尝试遍历 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/

相关文章:

python - Pandas:带有两个条形图和两个 y 轴的条形图

python - 使用 Pandas 将 JSON 列添加到模式中

python - Dask中compute()的目的

python - ImageDataGenerator流函数的正确使用

python - 无法在 Mac 上安装 mysqlclient

python - 如何在Python中指定对象被垃圾收集时的清理行为?

python - MySQL 的 read_sql() 非常慢

python - 如何在 Python Scrapy 上禁用 SSL 验证?

pandas - 查找被视为 float 但实际上可以写为整数的 pandas dataframe 列

r - 在维护行名称的 R 中对 data.frame 进行排序