首页 > 解决方案 > 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

标签: pythonpandasnumpy

解决方案


您可以使用管道字符连接列的所有行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

推荐阅读