将dict放入数据帧 - python

时间:2017-03-29 16:28:24

标签: python pandas dictionary

我有一个名为' gender'的列表,其中我用计数器计算了所有值的出现次数:

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})

我想把这个dict放到pandas Dataframe中。我使用过pd.series(Convert Python dict into a dataframe):

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

这给了我想要的数据帧,但我不知道如何将这些步骤保存到pandas DataFrame中。 我也尝试过使用DataFrame.from_dict()

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

但这会创建一个以性别类别为索引的数据框。

我最终想要使用性别类别和饼图计数。

3 个答案:

答案 0 :(得分:3)

略过中间步骤

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

答案 1 :(得分:2)

In [21]: df = pd.Series(gender_count).rename_axis('gender').reset_index(name='count')

In [22]: df
Out[22]:
              gender  count
0                  2      1
1  All Female Group,    222
2    All Male Group,    119
3            Couple,    256
4            Female,   1738
5              Male,   2077
6       Mixed Group,    212
7                 NA     16

答案 2 :(得分:0)

只是

client