我的 df 看起來像這樣:
| 索引1 | 索引2 | 貓 | 藝術 |
|---|---|---|---|
| ID | 1 | 1293874 | 優質的 |
| 姓名 | 1 | 山姆 | 老的 |
| ID | 2 | 2030039 | 退休 |
| 姓名 | 2 | 本 | 無欲無求 |
我的目標是嘗試旋轉 index1 并將它們添加為列。目前,我的資料結構不正確,格式不正確。類別列有一個名稱和id的資訊桶,但它不是類別。我不僅想按索引分組,而且還想在不洗掉任何原始列的情況下將列添加到資料集中。
我想要的輸出看起來像這樣
| 索引2 | 貓 | 姓名 | id_Art | 名稱_藝術 |
|---|---|---|---|---|
| 1 | 1293874 | 山姆 | 優質的 | 老的 |
| 2 | 2030039 | 本 | 退休 | 無欲無求 |
uj5u.com熱心網友回復:
您可以在 level=0 上使用 unstack(在您的情況下為 Index1):
df.set_index(['Index1', 'Index2'], inplace=True) #make sure your Index1 and Index2 are set are index
print(df.unstack(level=0))
輸出:
cat art
Index1 id name id name
Index2
1 1293874 Sam Vintage old
2 2030039 Ben Retired lacklust
uj5u.com熱心網友回復:
獲得與 Tranbi 的答案相同結果的另一種方法,因為您提到了旋轉:
df.pivot(index='Index2', columns='Index1')
給
cat art
Index1 id name id name
Index2
1 1293874 Sam Vintage old
2 2030039 Ben Retired lacklust
uj5u.com熱心網友回復:
您可以使用melt:
out = (df.melt(['Index1', 'Index2'], var_name='Category', value_name='Value')
.assign(Category=lambda x: x['Index1'] '_' x['Category'])
.pivot('Index2', 'Category', 'Value')
.rename_axis(columns=None).reset_index())
print(out)
# Output
Index2 id_art id_cat name_art name_cat
0 1 Vintage 1293874 old Sam
1 2 Retired 2030039 lacklust Ben
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451429.html
