Skip to content Skip to sidebar Skip to footer

Python Dictionary To Pandas Dataframe With Multiple Columns

I have the following python dictionary: d= {'data' : Counter({ 'important' : 2, 'very' : 3}), 'analytics' : Counter({ 'boring' : 5,

Solution 1:

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

Post a Comment for "Python Dictionary To Pandas Dataframe With Multiple Columns"