Merging and subtracting DataFrame columns in pandas?

后端 未结 3 969
我在风中等你
我在风中等你 2020-12-31 11:38

I have a pandas DataFrame, something like:

col1  col2 col3 col5
NaN    1    2    8
2     NaN   4    8
4     NaN   4    8

I want to do two t

3条回答
  •  感动是毒
    2020-12-31 11:56

    In [58]:
    
    df['newcol'] = df[['col1','col2']].sum(axis=1) - df['col5']
    df['col3'] = df['col3'] - df['col5']
    df
    Out[58]:
       col1  col2  col3  col5  newcol
    0   NaN     1    -6     8      -7
    1     2   NaN    -4     8      -6
    2     4   NaN    -4     8      -4
    

    You can then drop col1 and col2:

    In [59]:
    
    df = df.drop(['col1','col2'],axis=1)
    df
    Out[59]:
       col3  col5  newcol
    0    -6     8      -7
    1    -4     8      -6
    2    -4     8      -4
    

提交回复
热议问题