熊猫通过较大的分割字符串分组单个元素

时间:2020-09-09 15:04:41

标签: python-3.x pandas pandas-groupby

我有2500万行df,其中一列电影类型用“ |”分隔字符:

   userId  movieId  rating   timestamp                title                       genres
0       1      296     5.0  1147880044  Pulp Fiction (1994)  Comedy|Crime|Drama|Thriller
1       3      296     5.0  1439474476  Pulp Fiction (1994)  Comedy|Crime|Drama|Thriller
2       4      296     4.0  1573938898  Pulp Fiction (1994)  Comedy|Crime|Drama|Thriller
3       5      296     4.0   830786155  Pulp Fiction (1994)  Comedy|Crime|Drama|Thriller
4       7      296     4.0   835444730  Pulp Fiction (1994)  Comedy|Crime|Drama|Thriller 

我想通过独特的类型获得平均评分。

我可以使用以下方法提取所有独特的流派:

genres = pd.unique(df2['genres'].str.split('|', expand=True).stack())

哪个产量:

['Adventure' 'Animation' 'Children' 'Comedy' 'Fantasy' 'Romance' 'Drama'
 'Action' 'Crime' 'Thriller' 'Horror' 'Mystery' 'Sci-Fi' 'IMAX'
 'Documentary' 'War' 'Musical' 'Western' 'Film-Noir' '(no genres listed)']

我可以使用(设置类型等于有效类型)来隔离包含特定类型的行:

result[result['genres'].str.contains(genre)]

我发现附近有东西:pandas: Group by splitting string value in all rows (a column) and aggregation function

但是我似乎无法通过语法来对每种类型进行分组,因此我可以获得每种类型的平均评分。

1 个答案:

答案 0 :(得分:2)

使用DataFrame.assignSeries.str.splitDataFrame.explodeGroupBy.mean

dfg = (
    df.assign(genres=df["genres"].str.split("|"))
    .explode("genres")
    .groupby("genres", as_index=False)["rating"].mean()
)
     genres  rating
0    Comedy     4.4
1     Crime     4.4
2     Drama     4.4
3  Thriller     4.4