Samira Kumar
Samira Kumar

Reputation: 521

Pandas reposition column values based on values

I've this sample table as below:


|col_1|col_2|col_3|
|---|---|---|
|dog|cat|bike|
|cat|bike|dog|
|NaN|car|NaN|

In pandas, is there any method to rearrange the column values for each row such that all same values are in same column as below:


|col_1|col_2|col_3|col_4|
|---|---|---|
|dog|cat|bike|NaN|
|dog|cat|bike|NaN|
|NaN|NaN|NaN|car|

Missing values should be replaced with NaN. Thanks.

Upvotes: 0

Views: 40

Answers (1)

BENY
BENY

Reputation: 323226

This is more like a get_dummies problem

s=df.stack().str.get_dummies()
yourdf=s.sum(level=0).mul(s.columns)
yourdf
   bike  car  cat  dog
0  bike       cat  dog
1  bike       cat  dog
2        car          

Upvotes: 1

Related Questions