【问题标题】:How can I calculate the 3 genres most frequent it in python pandas?如何计算 python pandas 中最常见的 3 种类型?
【发布时间】:2019-04-25 10:52:23
【问题描述】:

我有一个包含一列的数据框,我需要返回 3 个最常见的流派。

输入

    genres
0   Drama
1   Animation|Children's|Musical
2   Musical|Romance
3   Drama
4   Animation|Children's|Comedy
5   Action|Adventure|Comedy|Romance
6   Action|Adventure|Drama
7   Comedy|Drama
8   Animation|Children's|Musical
9   Adventure|Children's|Drama|Musical
10  Animation|Children's|Musical
11  Musical
12  Drama
13  Comedy

剧情 6 音乐剧 6 儿童 5 动画4 喜剧 4 冒险 3 行动 2

OUTPUT - 包含以下内容的数据框:

  genres
0 Drama
1 Musical
2 Children's

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 你说你有一列的数据框,但那看起来不像一列?
  • 我尝试在虚拟表中分离并计算列的频率,但并不总是相同的列可以是其他类型
  • 一些minimal reproducible example 的尝试会很好......

标签: python pandas data-science


【解决方案1】:

您首先需要split,然后使用stack,然后使用value_counts

df.genres.str.split('|',expand=True).stack().value_counts().head(3)
Drama         6
Musical       6
Children's    5
dtype: int64

【讨论】:

  • 我需要获取流派名称,如何将索引名称放入列表中?
  • @Mariana df.genres.str.split('|',expand=True).stack().value_counts().head(3).index.tolist()
猜你喜欢
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
相关资源
最近更新 更多