![](/img/trans.png)
[英]Pandas pivot dataframe and setting the new columns as True/False based on if they existed or not
[英]Pandas crosstab dataframe and setting the new columns as True/False/Null based on if they existed or not and based on another column
正如標題所述,我想對我的 dataframe 進行透視/交叉表
假設我有一個看起來像這樣的 df:
df = pd.DataFrame({'ID' : [0, 0, 1, 1, 1],
'REV' : [0, 0, 1, 1, 1],
'GROUP' : [1, 2, 1, 2, 3],
'APPR' : [True, True, NULL, NULL, True})
+----+-----+-------+------+
| ID | REV | GROUP | APPR |
+----+-----+-------+------+
| 0 | 0 | 1 | True |
| 0 | 0 | 2 | True |
| 1 | 1 | 1 | NULL |
| 1 | 1 | 2 | NULL |
| 1 | 1 | 3 | True |
+----+-----+-------+------+
我想做某種 pivot 所以我的表格結果看起來像
+----+-----+------+------+-------+
| ID | REV | 1 | 2 | 3 |
+----+-----+------+------+-------+
| 0 | 0 | True | True | False |
| 1 | 1 | NULL | NULL | True |
+----+-----+------+------+-------+
現在 GROUP 列中的值變成了自己的列。 這些列中的每一個的值都是基於 APPR 的 T/F/NULL,僅適用於 T/NULL 部分。 當 ID REV 組合不存在該組時,我希望它為 False。
我之前問過類似的問題,但我不知道如何使這個答案適用於我的新場景: Pandas pivot dataframe 並將新列設置為 True/False 是否基於
希望這是有道理的!
你試過pivot嗎?
pd.pivot(df, index=['ID','REV'], columns=['GROUP'], values='APPR').fillna(False).reset_index()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.