在熊猫系列字典的计数值

时间:2021-01-07 14:47:25

标签: python pandas count

我有熊猫系列类型的字典是这样的:

print(df['genres'])
0                        {'0': '1', '1': '4', '2': '23'}
1             {'0': '1', '1': '25', '2': '4', '3': '37'}
2                                             {'0': '9'}

print(type(df['genres']))
<class 'pandas.core.series.Series'>

print(type(df['genres'][0]))
<class 'dict'>

我要计数的值来获得这样的:

{'1': 2, '4': 2, '9': 1, '23': 1, '25': 1, '37': 1}

我尝试了以下方法:

print(Counter(chain.from_iterable(df.genres.values)))
Counter({'0': 3, '1': 2, '2': 2, '3': 1})

print(pd.Series(df['genres']).value_counts())
{'0': '1', '1': '4', '2': '23'}                                  1
{'0': '1', '1': '25', '2': '4', '3': '37'}                       1
{'0': '9'}                                                       1

我觉得这是很容易让一个人比我更有经验。但我真的不明白这一点...

1 个答案:

答案 0 :(得分:0)

试试:

pd.DataFrame(list(df.genres)).stack().value_counts().to_dict()

输出:

{'1': 2, '4': 2, '37': 1, '9': 1, '23': 1, '25': 1}