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

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数据框中我用过PD系列(Convert Python dict into a dataframe):
s = pd.Series(gender_count, name='gender count')
s.index.name = 'gender'
s.reset_index()

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

但这会创建一个以性别类别为索引的数据框架。
我最终想使用性别分类和一个饼图的计数。

最佳答案

跳过中间步骤

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

关于python - 将字典放入数据框-python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43099154/

10-09 17:10
查看更多