python中分类列下的模式值以列表的形式出现



我使用下面的代码来获取分类列的模式:

df.groupby('user_id')['product'].agg(pd.Series.mode).reset_index().rename(columns = {'product': 'most_used_product'}).astype(str)

运行上述代码后,该列下的值以每个用户的列表形式出现,如:

['hat' 'shirt' 'shoes']
['hat' 'shoes']
['shirt'] 

当我尝试使用

选择column的值时
df[df['most_used_product']== "['hat' 'shirt' 'shoes']" 

我得到SyntaxError: invalid syntax。如何选择column的值?

你有两个错误,第一结束方括号,第二你的数据类型不是字符串,使用:

df[df['most_used_product'].astype(str)== "['hat', 'shirt', 'shoes']"]

最新更新