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

前端 未结 10 992
情歌与酒
情歌与酒 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
    
    0 讨论(0)
  • 2020-12-13 02:06

    Very simple:

    df['C'] = df['A'] + df['B']
    
    0 讨论(0)
  • 2020-12-13 02:06

    Can do using loc

    In [37]:  df = pd.DataFrame({"A":[1,2,3],"B":[4,6,9]})
    
    In [38]: df
    Out[38]:
       A  B
    0  1  4
    1  2  6
    2  3  9
    
    In [39]: df['C']=df.loc[:,['A','B']].sum(axis=1)
    
    In [40]: df
    Out[40]:
       A  B   C
    0  1  4   5
    1  2  6   8
    2  3  9  12
    
    0 讨论(0)
  • 2020-12-13 02:06

    You can solve it by adding simply: df['C'] = df['A'] + df['B']

    0 讨论(0)
  • 2020-12-13 02:08

    Building a little more on Anton's answer, you can add all the columns like this:

    df['sum'] = df[list(df.columns)].sum(axis=1)
    
    0 讨论(0)
  • 2020-12-13 02:09

    You could do:

    df['C'] = df.sum(axis=1)
    

    If you only want to do numerical values:

    df['C'] = df.sum(axis=1, numeric_only=True)
    
    0 讨论(0)
提交回复
热议问题