My pandas dataframe has separate columns that are one-hot encoded and a total column at the end that sums them up ( total
= val1
+ val2
).
Some rows have 1s for multiple val columns:
| name | val1 | val2 | total |
| joe | 1 | 0 | 1 |
| bob | 0 | 1 | 1 |
| dan | 1 | 1 | 2 |
I want this:
| name | val1 | val2 | total |
| joe | 1 | 0 | 1 |
| bob | 0 | 1 | 1 |
| dan | 1 | 0 | 1 |
| dan | 0 | 1 | 1 |
I can't figure out how to get this to work: to melt it conditional upon the total column.
The end result should have a total value of 1 for every row.
d = df.drop('total', axis=1).set_index('name').stack().loc[lambda x: x == 1]
n, v = zip(*d.index)
pd.concat([pd.Series(n, name='name'), pd.get_dummies(v).assign(total=1)], axis=1)
name val1 val2 total
0 joe 1 0 1
1 bob 0 1 1
2 dan 1 0 1
3 dan 0 1 1
Harder than what I thought
s1=df.iloc[:,1:-1]
s2=df.iloc[:,0]
df[['name']].join(s1.mul(s2,0).replace('',np.nan).stack().reset_index(level=1)['level_1'].str.get_dummies(),how='right').assign(Total=1)
Out[413]:
name val1 val2 Total
0 joe 1 0 1
1 bob 0 1 1
2 dan 1 0 1
2 dan 0 1 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.