【问题标题】:Finding count of string(seperated by delimeter) in data frame?在数据框中查找字符串的计数(由分隔符分隔)?
【发布时间】:2019-12-16 15:26:37
【问题描述】:

我有这个数据框。

df

   userId  movieId  rating                genres
0      41    97921    4.0          Comedy|Drama|Sci-Fi
1      47    97921    3.5          Comedy|Drama|Sci-Fi
2     594    539      5.0          Comedy|Drama|Romance|Adventure
3       4    539      5.0          Comedy|Drama|Romance|Adventure
4     113    1733     4.0          Drama|Romance
5     594    1733     5.0          Drama|Romance

我还有所有类型的列表:

genres = ['Comedy','Drama','Romance','Action','Adventure','Sci-Fi','Thriller','Crime',\
          'Animation','Children','Musical','Film-Noir','Fantasy','War','Mystery','IMAX',\
             'Horror','Western','Documentary' ]

我想统计数据框中的每个类型。

Expected Output:
Comedy :4
Drama :6
Sci-Fi: 2
Romance: 2
Adventure: 2

【问题讨论】:

    标签: python-3.x pandas split count


    【解决方案1】:

    你可以使用:

    df['genres'].str.split('|').explode().value_counts().to_dict() #requires pandas 0.25+
    
    #{'Drama': 6, 'Comedy': 4, 'Romance': 4, 'Sci-Fi': 2, 'Adventure': 2}
    

    或者:

    df['genres'].str.get_dummies().sum().to_dict()
    #{'Adventure': 2, 'Comedy': 4, 'Drama': 6, 'Romance': 4, 'Sci-Fi': 2}
    

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2022-12-19
      相关资源
      最近更新 更多