df3['col_two']具有电影类型的嵌套列表。我试着为每一行关于这些类型的假人。我想我遇到的问题是str.get\u dummies()很管用,但它当然会把“冒险”和“冒险”当作两个不同的东西来读,但我想要的显然是每个流派都有一个专栏(即一个专栏代表冒险)
我尝试过pd.series.replace(),如下所示:
df3['col_two'].replace({'[':''})
或者像这样的数组
df3['col_two'] = np.array(df3['col_two'])
但它们都给出了相同的错误:
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
df['genres'] = df['genres'].str.split(pat='|')
df3 = pd.melt(df, id_vars=['id'], value_vars=['genres'], var_name='col_one',
value_name='col_two')
df3.head()
id col_one col_two
0 135397 genres [Action, Adventure, Science Fiction, Thriller]
1 76341 genres [Action, Adventure, Science Fiction, Thriller]
2 262500 genres [Adventure, Science Fiction, Thriller]
3 140607 genres [Action, Adventure, Science Fiction, Fantasy]
4 168259 genres [Action, Crime, Thriller]
df4 = df3["col_two"].str.get_dummies(",")
df4.head()
'Action' 'Action'] 'Adventure' 'Adventure'] 'Animation' 'Animation'] 'Comedy' 'Comedy'] 'Crime' 'Crime'] ... ['Romance'] ['Science Fiction' ['Science Fiction'] ['TV Movie' ['Thriller' ['Thriller'] ['War' ['War'] ['Western' ['Western']
0 0 0 1 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
3 0 0 1 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 1 0 ... 0 0 0 0 0 0 0 0 0 0
我想做的是每个流派有一个列,没有奇怪的重复,因为不需要额外的字符,如“]”等,以及通常的0或1虚拟变量沿列
为最后一个df的奇怪布局道歉,并提前感谢您的每一个回答
可以使用
str.translate
和str.maketrans
删除字符,然后使用get_dummies
:这个post和
str.translate
的documentation应该提供更多关于参数的信息dummified列的一个简单的.join应该可以很好地工作。试试这个:
让我知道这是否适合你
相关问题 更多 >
编程相关推荐