Hrvoje
Hrvoje

Reputation: 15202

One-hot encoding with pd.get_dummies - show only columns with value 1 for chosen row

After one-hot encoding of my used cars dataset with X = pd.get_dummies(data=X) I need to see column which holds value of 1 for certain row. So if I select row like this:

 X.iloc[0,:]

I would get (I'm pasting only portion of the output):

model_106                         0
model_116                         0
model_118                         0
model_120                         0
model_124                         0
model_146                         0
model_147                         0
model_156                         0
model_159                         0
model_166                         0
model_190                         0
model_2                           0
model_206                         0
model_207                         0
model_208                         0

I need to find only columns which has value 1 for coresponding row. Other columns should be hidden. How can I do that?

Upvotes: 0

Views: 34

Answers (2)

ansev
ansev

Reputation: 30930

You need to use boolean indexing with DataFrame.loc:

df.loc[df.index[0],df.iloc[0].eq(1)]

Upvotes: 1

Rajith Thennakoon
Rajith Thennakoon

Reputation: 4130

hope this will helpful,lets take your dataframe as df and your required column names as cols

 df_= df[cols]
 result = df_.idxmax(axis=1).tolist()

Upvotes: 0

Related Questions