Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a dict into a dataframe - python

I have a list called 'gender', of which I counted all the occurrences of the values with Counter:

gender = ['2',
          'Female,',
          'All Female Group,',
          'All Male Group,',
          'Female,',
          'Couple,',
          'Mixed Group,'....]

gender_count = Counter(gender)
gender_count 
Counter({'2': 1,
     'All Female Group,': 222,
     'All Male Group,': 119,
     'Couple,': 256,
     'Female,': 1738,
     'Male,': 2077,
     'Mixed Group,': 212,
     'NA': 16})

I want to put this dict into a pandas Dataframe. I have used pd.series(Convert Python dict into a dataframe):

s = pd.Series(gender_count, name='gender count')
s.index.name = 'gender'
s.reset_index()

Which gives me the dataframe I want, but I don't know how to save these steps into a pandas DataFrame. I also tried using DataFrame.from_dict()

s2 = pd.DataFrame.from_dict(gender_count, orient='index')

But this creates a dataframe with the categories of gender as the index.

I eventually want to use gender categories and the count for a piechart.

like image 402
Lisadk Avatar asked Aug 07 '26 14:08

Lisadk


1 Answers

Skip the intermediate step

gender = ['2',
          'Female',
          'All Female Group',
          'All Male Group',
          'Female',
          'Couple',
          'Mixed Group']

pd.value_counts(gender)

Female              2
2                   1
Couple              1
Mixed Group         1
All Female Group    1
All Male Group      1
dtype: int64
like image 112
piRSquared Avatar answered Aug 09 '26 02:08

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!