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

Viewed 99

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!

3 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
...

Pass it as a list

pd.DataFrame([d]).T.rename(columns={0:'count'})

That might get the work done but will kill the performance since we are saying the keys are columns and then transposing it. So since d.items() gives us the tuples we can do

df = pd.DataFrame(list(d.items()),columns=['country','count'])

df.head()
    country  count
0       Germany      3
1   Philippines      8
2        Mexico      9
3       Nigeria      9
4  Saudi Arabia      9

Use DataFrame constructor and pass values and keys separately to columns:

df = pd.DataFrame({'Country':list(d.keys()), 
                   'Count': list(d.values())}, columns=['Country','Count'])
print (df)
          Country  Count
0      Azerbaijan      5
1       Indonesia      3
2         Germany      3
3          France     12
4          Mexico      9
5           Italy      2
6           Spain      5
7          Brazil      3
8        Thailand      5
9       Argentina      9
10        Ukraine      3
11  United States     38
12         Turkey      2
13        Nigeria      9
14   Saudi Arabia      9
15    Philippines      8
16          China      1
17          Japan     60
18         Russia      3
19          India     18
20    Netherlands      8
Related