Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change this form of dictionary to pandas dataframe?

I'm now processing tweet data using python pandas module, and I stuck with the problem.

I want to make a frequency table(pandas dataframe) from this dictionary:

d = {"Nigeria": 9, "India": 18, "Saudi Arabia": 9, "Japan": 60, "Brazil": 3, "United States": 38, "Spain": 5, "Russia": 3, "Ukraine": 3, "Azerbaijan": 5, "China": 1, "Germany": 3, "France": 12, "Philippines": 8, "Thailand": 5, "Argentina": 9, "Indonesia": 3, "Netherlands": 8, "Turkey": 2, "Mexico": 9, "Italy": 2}

desired output is:

>>> import pandas as pd
>>> df = pd.DataFrame(?????)
>>> df

Country      Count
Nigeria      9
India        18
Saudi Arabia 9
.
.
.

(no matter if there's index from 0 to n at the leftmost column)

Can anyone help me to deal with this problem? Thank you in advance!

like image 692
joopyter Avatar asked Dec 24 '22 12:12

joopyter


1 Answers

You have only a single series (a column of data with index values), really, so this works:

pd.Series(d, name='Count')

You can then construct a DataFrame if you want:

df = pd.DataFrame(pd.Series(d, name='Count'))
df.index.name = 'Country'

Now you have:

               Count
Country             
Argentina          9
Azerbaijan         5
Brazil             3
...
like image 194
John Zwinck Avatar answered Dec 28 '22 08:12

John Zwinck