我正在嘗試遍歷 content_with_genres1 資料框,然后將流派附加為 1 或 0 的列。但奇怪的是,這些流派已被視為一個字串,如圖所示。
這是我的代碼:
content_with_genres = content_refined.copy(deep=True)
content_with_genres1 = content_with_genres.drop(['content_type','language','rating'], axis=1)
x = []
for index, row in content_with_genres1.iterrows():
x.append(index)
for genre in row['genre']:
content_with_genres1.at[index, genre] = 1
print(len(x) == len(content_with_genres1))
content_with_genres1.head(5)
這就是我得到的 - 資料框
我希望資料框是這樣的:
content_id | genre | drama | comedy | action | sports
-------------------------------------------------------
cont_123 | drama | 1 | 0 | 0 | 0
cont_234 | comedy | 0 | 1 | 0 | 0
請幫助我提前謝謝
uj5u.com熱心網友回復:
IIUC,您正在尋找pd.get_dummies:
out = pd.concat([df, pd.get_dummies(df['genre'])], axis=1)
print(out)
# Output
content_id genre comedy drama
0 cont_123 drama 0 1
1 cont_456 comedy 1 0
設定:
>>> df
content_id genre
0 cont_123 drama
1 cont_456 comedy
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447941.html
上一篇:調查-DF1-問題在第1行,在DF2中,所有問題都列在第一列Python
下一篇:使用正則運算式將一列拆分為多個
