在pandas数据帧上迭代并更新值-attributeRor:无法设置attribu

2024-04-28 13:42:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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

Tags: and数据inpandasdfforif错误
3条回答

好的,如果要在df中设置值,则需要跟踪index值。

选项1
使用itertuples

# keep in mind `row` is a named tuple and cannot be edited
for line, row in enumerate(df.itertuples(), 1):  # you don't need enumerate here, but doesn't hurt.
    if row.Qty:
        if row.Qty == 1 and row.Price == 10:
            df.set_value(row.Index, 'Buy', 1)

选项2
使用iterrows

# keep in mind that `row` is a `pd.Series` and can be edited...
# ... but it is just a copy and won't reflect in `df`
for idx, row in df.iterrows():
    if row.Qty:
        if row.Qty == 1 and row.Price == 10:
            df.set_value(idx, 'Buy', 1)

选项3
使用带get_value的直上循环

for idx in df.index:
    q = df.get_value(idx, 'Qty')
    if q:
        p = df.get_value(idx, 'Price')
        if q == 1 and p == 10:
            df.set_value(idx, 'Buy', 1)

从0.21.0pd.DataFrame.set_value起,不推荐使用pandas.DataFrame.set_value方法

使用pandas.Dataframe.at

for index, row in df.iterrows():
        if row.Qty and row.Qty == 1 and row.Price == 10:
            df.at[index,'Buy'] = 1

第一次在pandas中迭代是可能的,但是非常慢,因此使用另一个矢量化的解决方案。

如果需要迭代,可以使用^{}

for idx, row in df.iterrows():
    if  df.loc[idx,'Qty'] == 1 and df.loc[idx,'Price'] == 10:
        df.loc[idx,'Buy'] = 1

但更好的方法是使用矢量化的解决方案-使用loc按布尔掩码设置值:

mask = (df['Qty'] == 1) & (df['Price'] == 10)
df.loc[mask, 'Buy'] = 1

或者用^{}的溶液:

df['Buy'] = df['Buy'].mask(mask, 1)

或者如果您需要if...else使用^{}

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

相关问题 更多 >