python-3.x - 我如何计算 DataFrame 中的所有流派?

标签 python-3.x pandas list dataframe dictionary

我有一个名为 df_imdb 的 DataFrame:

enter image description here

每一行包含有关一部电影的信息,此 DataFrame 有一个列名称“流派”,显示该电影的流派,该电影可能有多个流派,例如[{'id': 53, 'name': '惊悚'}, {'id': 28, 'name': ' Action '}, {'id': 9648, 'name': '神秘' }]

我想找出这部电影中使用最多的类型(在此 DataFrame 中找到前 3 个最常用的类型)

最佳答案

数据是字典列表,这里有多个选项:

选项 1:纯 pandas,将与键 name 关联的值转换为 Series 并使用 value_counts

df = pd.DataFrame({'genres':[[{'id': 53, 'name': 'Thriller'}, {'id': 28, 'name': 'Action'}, {'id': 9648, 'name': 'Mystery'}],[{'id': 53, 'name': 'Thriller'}, {'id': 30, 'name': 'Blah'}, {'id': 9648, 'name': 'Mystery'}]]})

df['genres'].apply(lambda x: pd.Series([i['name'] for i in x]))\
.stack().value_counts()

你得到了

Thriller    2
Mystery     2
Action      1
Blah        1

选项 2:将值转换为列表并使用 Counter

from collections import Counter
l_genres = df['genres'].apply(lambda x: [i['name'] for i in x]).sum()
Counter(l_genres)

你得到了

Counter({'Thriller': 2, 'Action': 1, 'Mystery': 2, 'Blah': 1})

df['genres'].apply(lambda x: pd.Series([i['name'] for i in x])).stack().value_counts()

编辑:数据类型是str而不是list,首先使用literal_eval

from ast import literal_eval
df['genres'] = df['genres'].apply(literal_eval)

关于python-3.x - 我如何计算 DataFrame 中的所有流派?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65324814/

相关文章:

python - 嵌套/转义 f 字符串 "="(等号)表达式

具有过滤功能的Python列表(excel-way)

python - 如何从日期时间推断季度?

python - 在python中,是否有一种有效的方法来将一个数组与映射到另一个数组的元素分开?

python - 从列表中删除 unicode 'u' 的最简单方法是什么

list - 如何在 Emacs Lisp 中设置列​​表中的部分参数?

python-3.x - 在Python中对具有多个小数点的字典和字符串中的键进行排序

python - “Popen”对象不可迭代

bash - 找不到subprocess.Popen返回命令

python - 从数据框列检查字符串是否为 nan