I have this data
ID A B C
0 0 True False False
1 1 False True False
2 2 False False True
And want to transform it into
ID group
0 0 A
1 1 B
2 2 C
category
column.True
value per row.This is the MWE
#!/usr/bin/env python3
import pandas as pd
df = pd.DataFrame({
'ID': range(3),
'A': [True, False, False],
'B': [False, True, False],
'C': [False, False, True]
})
result = pd.DataFrame({
'ID': range(3),
'group': ['A', 'B', 'C']
})
result.group = result.group.astype('category')
print(df)
print(result)
I could do df.apply(lambda row: ...magic.., axis=1)
. But isn't there a more elegant way with pandas' own tools?
You can use df.dot
:
df['group'] = df[['A', 'B', 'C']].dot(df.columns[1:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With