python - Python查询具有管道分隔列的数据框
问题描述
数据框包含管道分隔的列和其他不分隔的列。为了找到最受欢迎的类型,我使用下面的代码来计算唯一值的数量。但是,如何处理管道以返回真正最受欢迎的类型?
df.genres.value_counts()
结果:
Drama 712
Comedy 712
Documentary 312
Drama|Romance 289
Comedy|Drama 280
...
TV Movie|Animation|Fantasy 1
Science Fiction|Action|Comedy|Horror 1
Drama|Comedy|Thriller|Romance|Foreign 1
Horror|Animation|Mystery 1
Romance|Comedy|Drama|Music 1
Name: genres, Length: 2039, dtype: int64
df.head()
id runtime genres
0 135397 124 Action|Adventure|Science Fiction|Thriller
1 76341 120 Action|Adventure|Science Fiction|Thriller
2 262500 119 Adventure|Science Fiction|Thriller
3 140607 136 Action|Adventure|Science Fiction|Fantasy
4 168259 137 Action|Crime|Thriller
df.dtypes
id int64
runtime int64
genres object
解决方案
您可以使用管道字符连接列的所有行genres
,然后根据管道重新拆分它们。通过这种方式,您可以获得所有流派的列表,无论它们最初是否是管道分隔的。
df = pd.DataFrame({'genres': ['Drama', 'Comedy', 'Documentary', 'Drama|Romance', 'Comedy|Romance', 'Documentary|Romance']})
popular_list = '|'.join(df['genres']).split('|')
print(popular_list)
输出:
['Drama', 'Comedy', 'Documentary', 'Drama', 'Romance', 'Comedy', 'Romance', 'Documentary', 'Romance']
然后,如果需要,只需找到频率最高的项目和相应的计数:
true_most_popular = max(set(popular_list), key = popular_list.count)
print(true_most_popular)
print(popular_list.count(true_most_popular))
输出:
Romance
3
推荐阅读
- javascript - Topojson沿海省份
- ansible - 何时评估 with_items 内的值列表的条件
- javascript - Electron 与 Vue.js,不使用样板
- asp.net - 从 ApplicationUser 继承返回 null
- r - 使用 grepl 进行双 for 循环过滤数据帧
- ecmascript-6 - 解构时可空嵌套对象上的 ES6 默认参数
- wix - 用于 2 个组件的 WiX 安装程序
- android - 如何将 ImageView 放在边界半径顶部的 CardView 内?
- c++ - 如何在同一行打印和更新记分牌?
- php - 实时服务器上的 SMTP 连接失败 PhpMailer