如何通过从for循环中获取值将新值分配给Dataframe列

时间:2019-06-06 13:52:35

标签: pandas-groupby

我想在dataframe(df)中添加一个新列(C),该列应包含基于df_inv [“ Item_Qty”]。sum()的值,方法是循环df,例如: 对于inv,在df.groupby(“ Inv_No”)中的df_inv

df = pd.DataFrame({
    'Item':     ['Table1', 'Locks', 'Bed', 'Domains', 'Table2','Chair','Table3'],
    'column':     ['col_1', 'col_2', 'col_3', 'col_4', 'col_5','col_6','col_7'],
    'Item_Qty' :     [1,1,1,1,5,2,2],
    'Price' : [40,20,30,20,40,20,40],
    'Inv_No': [111,222,333,222,111,222,111],
    'CARGO' : [1,0,0,0,1,0,1],
    'Item_Price': [5,20,30,20,5,20,5]


})


def itemfix_cargo(df):
    if df.CARGO ==1:
        for inv,df_inv in df.groupby("Inv_No").any():
            sm = df_inv["Item_Qty"].sum()
            b =0.25*df.Item_Price
            df["Item_Price_New"] =max(8/sm,b)
    return df

df=df.apply(itemfix_cargo,axis=1)

My Expected result is:

    Item    column  Item_Qty    Price   Inv_No  CARGO   Item_Price  Item_Price_New
0   Table1  col_1   1   40  111 1   5   1.25
1   Locks   col_2   1   20  222 0   20  20.00
2   Bed col_3   1   30  333 0   30  30.00
3   Domains col_4   1   20  222 0   20  20.00
4   Table2  col_5   5   40  111 1   5   1.25
5   Chair   col_6   2   20  222 0   20  20.00
6   Table3  col_7   2   40  111 1   5   1.25

but when I run this 

df=df.apply(itemfix_cargo,axis=1)

I get following error:

      1 def itemfix_cargo(df):
      2     if df.CARGO ==1:
----> 3         for inv,df_inv in a.any():
      4             sm = df_inv["Item_Qty"].sum()
      5             b =0.25*df.Item_Price

ValueError :(“要解压缩的值太多(预期2)”,“发生在索引0”)

我尝试了不同的方法进行循环,但是遇到相同的错误。 谁能帮助我更正相同的代码。预先感谢。

0 个答案:

没有答案