我有一個這樣的資料框:
df = pd.DataFrame({"id": [1, 2, 2, 1, 3, 3, 2, 1, 2],
"colors": ['green', 'blue', 'green', 'yellow', 'yellow', 'yellow', 'green', 'red', 'black']
所以有兩個長度相同但在 id 和顏色之間沒有邏輯模式的系列。例如 id 1 可以是藍綠色、紅色等。
我想做的是創建另一個資料框,其中每個唯一ID 的第一行和下一行包含所有可能顏色的計數。
在我的示例中,我希望結果為:
| ID | 綠色 | 藍色的 | 黃色 | 紅色的 | 黑色的 |
|---|---|---|---|---|---|
| 1 | 1 | 0 | 1 | 1 | 0 |
| 2 | 2 | 1 | 0 | 0 | 1 |
| 3 | 0 | 0 | 2 | 0 | 0 |
我嘗試:但 == 不起作用。
print(df.loc[df.id.unique() == df["id"], "colors"].value_counts())
uj5u.com熱心網友回復:
你可以使用pivot_table:
df.pivot_table(index="id", columns="colors", aggfunc=len, fill_value=0)
# out:
colors black blue green red yellow
id
1 0 0 1 1 1
2 1 1 2 0 0
3 0 0 0 0 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486547.html
下一篇:結合熊貓資料框的假人和計數
