Sum the values in a pandas column based on the items in another column

后端 未结 2 932
醉梦人生
醉梦人生 2021-01-29 00:33

how can I sum the values in column \'two\' based on the items in column \'one\' in pandas dataframe:

df = pd.DataFrame({\'One\': [\'A\', \'B\', \'A\', \'B\'], \'         


        
相关标签:
2条回答
  • 2021-01-29 00:52

    The trick is use pandas built-in functions .groupby(COLUMN_NAME) and then .sum() that new pandas object

    import pandas as pd
    df = pd.DataFrame({'One': ['A', 'B', 'A', 'B'], 'Two': [1, 5, 3, 4]})
    
    groups = df.groupby('One').sum()
    print(groups.head())
    
    0 讨论(0)
  • 2021-01-29 00:58

    You need to group by the first column and sum on the second.

    df.groupby('One', as_index=False).sum()
    
      One  Two
    0   A    4
    1   B    9
    
    0 讨论(0)
提交回复
热议问题