如何对特定列的行的值求和?

时间:2018-03-03 09:48:12

标签: python pandas

             NYSEARCA:RYE  NYSEARCA:RYE_totalunits  NYSEARCA:PXE  NYSEARCA:PXE_totalunits
Date                                                                 
2007-12-31         1              2                           6         3                                  
2008-01-31         2              3                           6         4   
2008-02-29         3              4                           3         5   
2008-03-31         4              5                           3         6   

如何在行中找到NYSEARCA:RYE_totalunits和NYSEARCA:PXE_totalunits的总和,以便我可以在名为total overall units的新列中实现此目的:

             NYSEARCA:RYE  NYSEARCA:RYE_totalunits  NYSEARCA:PXE  NYSEARCA:PXE_totalunits  Total overall units
Date                                                                 
2007-12-31         1              2                           6         3                   5                                  
2008-01-31         2              3                           6         4                   7     
2008-02-29         3              4                           3         5                   9   
2008-03-31         4              5                           3         6                   11  

1 个答案:

答案 0 :(得分:1)

首先过滤列,然后使用sum

cols = ['NYSEARCA:RYE_totalunits','NYSEARCA:PXE_totalunits']
df['new'] = df[cols].sum(axis=1)
print (df)
            NYSEARCA:RYE  NYSEARCA:RYE_totalunits  NYSEARCA:PXE  \
2007-12-31             1                        2             6   
2008-01-31             2                        3             6   
2008-02-29             3                        4             3   
2008-03-31             4                        5             3   

            NYSEARCA:PXE_totalunits  new  
2007-12-31                        3    5  
2008-01-31                        4    7  
2008-02-29                        5    9  
2008-03-31                        6   11