Make new column in Panda dataframe by adding values from other columns

前端 未结 10 1005
情歌与酒
情歌与酒 2020-12-13 01:59

I have a dataframe with values like

A B
1 4
2 6
3 9

I need to add a new column by adding values from column A and B, like

         


        
10条回答
  •  我在风中等你
    2020-12-13 02:03

    As of Pandas version 0.16.0 you can use assign as follows:

    df = pd.DataFrame({"A": [1,2,3], "B": [4,6,9]})
    df.assign(C = df.A + df.B)
    
    # Out[383]: 
    #    A  B   C
    # 0  1  4   5
    # 1  2  6   8
    # 2  3  9  12
    

    You can add multiple columns this way as follows:

    df.assign(C = df.A + df.B,
              Diff = df.B - df.A,
              Mult = df.A * df.B)
    # Out[379]: 
    #    A  B   C  Diff  Mult
    # 0  1  4   5     3     4
    # 1  2  6   8     4    12
    # 2  3  9  12     6    27
    

提交回复
热议问题