【问题标题】:Pandas: Split arrays and count [duplicate]熊猫:拆分数组和计数[重复]
【发布时间】:2022-01-18 05:20:21
【问题描述】:

我在 DataFrame 中有一个列,其中包含一个流派数组

Row 1 genres = [Action, Adventure, Science Fiction, Thriller]
Row 2 genres = [Action, Crime, Thriller]
and so on...

如何获得列中所有单个类型的计数?

决赛桌结果:

Action 2
Adventure 1
Thriller 2
Science Fiction 1
Crime 1

【问题讨论】:

  • “最终表格”不必与原始长度(行数)匹配。它只需要计算原始值中的所有唯一值
  • 您尝试了哪些方法,为什么没有成功?

标签: python arrays pandas dataframe arraylist


【解决方案1】:

鉴于此 DataFrame:

df = pd.DataFrame({'col':[['Action', 'Adventure', 'Science Fiction', 'Thriller'], ['Action', 'Crime', 'Thriller']]})

您可以explode 列并使用value_counts:

out = df['col'].explode().value_counts()

输出:

Action             2
Adventure          1
Crime              1
Science Fiction    1
Thriller           2
dtype: int64

【讨论】:

  • 这个答案比创建字典来存储 value_counts 并将函数应用于 pandas 列要好得多。不错
猜你喜欢
  • 2020-12-19
  • 2018-04-29
  • 2017-03-21
  • 2018-07-08
  • 2020-01-08
  • 2017-09-19
  • 1970-01-01
相关资源
最近更新 更多