Group pandas dataframe by a nested dictionary key

后端 未结 2 972
梦如初夏
梦如初夏 2021-01-20 17:32

I have a pandas dataframe where one of the columns is dictionary type. This is an example dataframe:

import pandas as pd
df = pd.DataFrame({\'a\': [1,2,3], 
         


        
相关标签:
2条回答
  • 2021-01-20 18:01

    you can do it this way:

    In [15]: df.assign(major=df.version.apply(pd.Series).major).groupby('major').sum()
    Out[15]:
           a   b
    major
    7      4  10
    8      2   5
    
    0 讨论(0)
  • 2021-01-20 18:15

    Option 1

    df.groupby(df.version.apply(lambda x: x['major'])).size()
    
    version
    7    2
    8    1
    dtype: int64
    

    df.groupby(df.version.apply(lambda x: x['major']))[['a', 'b']].sum()
    

    Option 2

    df.groupby(df.version.apply(pd.Series).major).size()
    
    major
    7    2
    8    1
    dtype: int64
    

    df.groupby(df.version.apply(pd.Series).major)[['a', 'b']].sum()
    

    0 讨论(0)
提交回复
热议问题