簡體   English   中英

pandas中get_dummies中如何指定刪除哪一列

[英]How to specify which column to remove in get_dummies in pandas

我有一個包含 3 個值的 DataFrame 列 - Bart、Peg、Human。 我需要對它們進行單熱編碼,使 Bart 和 Peg 保留為列,而人則表示為 0 0。

Xi | Architecture
0  | Bart
1  | Bart
2  | Peg
3  | Human
4  | Human
5  | Peg
..
.

我想對它們進行單熱編碼,以便 Human 表示為 0 0:

Xi |Bart| Peg
0  | 1  | 0
1  | 1  | 0
2  | 0  | 1
3  | 0  | 0
4  | 0  | 0
5  | 0  | 1

但是當我這樣做時:

pd.get_dummies(df['Architecture'], drop_first = True)

它刪除“Bart”並保留其他 2。有沒有辦法指定要刪除的列?

你可以mask它:

df = df[['Xi']].join(pd.get_dummies(df['Architecture'].mask(df['Architecture']=='Human')))

Output:

   Xi  Bart  Peg
0   0     1    0
1   1     1    0
2   2     0    1
3   3     0    0
4   4     0    0
5   5     0    1

IIUC,嘗試使用 get_dummies 然后刪除“人類”列:

df['Architecture'].str.get_dummies().drop('Human', axis=1)

Output:

   Bart  Peg
0     1    0
1     1    0
2     0    1
3     0    0
4     0    0
5     0    1

它正在刪除“Bart”,因為這是它看到的“第一個”label。 get_dummies沒有內置的方式說“在之后刪除此列”。 這很煩人。 所以你可以做幾件事:

  • 在使用get_dummies之前對數據集進行排序,以便在您首先使用drop first顯示“Human”
  • 將數據集子集僅對列進行單熱編碼,其中(體系結構 =“Bart”或“Peg”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM