How can I change this dictionary form to pandas dataframe?

Now I am processing the tweet data using the python pandas module, and I ran into a 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 result:

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

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

(regardless of whether the index exists from 0 to n in the leftmost column)

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

+4
source share
3 answers

You only have one series (data column with indexes), so this works:

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

Then you can build 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
...
+4
source

Pass it as a list

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

, , , , . d.items() ,

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

Use the constructor DataFrameand pass valuesand keysseparately to the 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
+3
source

Source: https://habr.com/ru/post/1689782/


All Articles