python dictionary to pandas dataframe with multiple columns

后端 未结 1 1668
没有蜡笔的小新
没有蜡笔的小新 2021-01-16 10:36

I have the following python dictionary:

d= {\'data\'      : Counter({ \'important\' : 2,
                        \'very\'      : 3}),
    \'analytics\' : Co         


        
相关标签:
1条回答
  • 2021-01-16 11:36

    You can use stack:

    df = pd.DataFrame(d).stack().reset_index()
    df.columns = ['word','category','count']
    print(df)
            word   category  count
    0     boring  analytics    5.0
    1  important       data    2.0
    2      sleep  analytics    3.0
    3       very       data    3.0
    

    df = pd.DataFrame.from_dict(d, orient='index').stack().reset_index()
    df.columns = ['category','word','count']
    print(df)
    
        category       word  count
    0  analytics     boring    5.0
    1  analytics      sleep    3.0
    2       data  important    2.0
    3       data       very    3.0
    

    Another solution with nested list comprehension:

    df = pd.DataFrame([(key,key1,val1) for key,val in d.items() for key1,val1 in val.items()])
    df.columns = ['category','word','count']
    print(df)
        category       word  count
    0  analytics     boring      5
    1  analytics      sleep      3
    2       data  important      2
    3       data       very      3
    
    0 讨论(0)
提交回复
热议问题