![](/img/trans.png)
[英]Pandas crosstab dataframe and setting the new columns as True/False/Null based on if they existed or not and based on another column
[英]Pandas pivot dataframe and setting the new columns as True/False based on if they existed or not
正如標題所說,我想 pivot 我的 dataframe (我相信它需要被旋轉?)
假設我有一個看起來像這樣的 df:
df = pd.DataFrame({'ID' : [0, 0, 1, 1, 1],
'REV' : [0, 0, 1, 1, 1],
'GROUP' : [1, 2, 1, 2, 3]})
+----+-----+-------+
| ID | REV | GROUP |
+----+-----+-------+
| 0 | 0 | 1 |
| 0 | 0 | 2 |
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 1 | 3 |
+----+-----+-------+
我想做某種 pivot 所以我的表格結果看起來像
+----+-----+------+------+-------+
| ID | REV | 1 | 2 | 3 |
+----+-----+------+------+-------+
| 0 | 0 | True | True | False |
| 1 | 1 | True | True | True |
+----+-----+------+------+-------+
現在 GROUP 列中的值變成了自己的列。 這些列中的每一個的值都是 T/F,取決於原始 df 是否具有該組。
有什么建議嗎? 這看起來像是 pivot 的東西,但在使用樞軸時我是個大菜鳥
我會使用get_dummies
然后groupby
與any
:
pd.get_dummies(df.set_index(["ID", "REV"]).GROUP).groupby(level=[0,1]).any()
1 2 3
ID REV
0 0 True True False
1 1 True True True
如果您希望將ID
和REV
列作為列而不是索引,則可以添加reset_index
:
pd.get_dummies(df.set_index(["ID", "REV"]).GROUP).groupby(level=[0,1]).any().reset_index()
ID REV 1 2 3
0 0 0 True True False
1 1 1 True True True
嘗試使用crosstab
out = pd.crosstab([df.ID,df.REV],df.GROUP).ne(0).reset_index().rename_axis(None,axis=1)
out
ID REV 1 2 3
0 0 0 True True False
1 1 1 True True True
您可以創建一個與GROUP
相同的虛擬列,然后將該虛擬列用作pivot_table()
中的值。
df['GROUP_'] = df['GROUP']
df_ = ~ pd.pivot_table(df, index=['ID', 'REV'], columns='GROUP', values='GROUP_').isna()
print(df_)
GROUP 1 2 3
ID REV
0 0 True True False
1 1 True True True
print(df_.reset_index().rename_axis(None,axis=1))
ID REV 1 2 3
0 0 0 True True False
1 1 1 True True True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.