I have a set of data like below:
name A B C
foo 1 0 0
bar 0 1 0
coo 0 0 1
That I am trying to alter to look like the table below:
name
A foo
B bar
C coo
I’ve done research but have gotten no luck. I’m not sure if it is possible within python. Do I need to manually change this table to get the result I am looking for?
Code
If there is a single 1 in every row, the following method is the simplest.
out = df.set_index('name').idxmax()
out
A foo
B bar
C coo
dtype: object
Example
import pandas as pd
data = {'name': ['foo', 'bar', 'coo'],
'A': [1, 0, 0], 'B': [0, 1, 0], 'C': [0, 0, 1]}
df = pd.DataFrame(data)
df
name A B C
0 foo 1 0 0
1 bar 0 1 0
2 coo 0 0 1
assuming the data is already in a dataframe df as you describe, try using a list comprehension:
result = pd.DataFrame({
‘name’: [df[‘name’][i] for col in [‘A’, ‘B’, ‘C’] for i in range(len(df)) if df[col][i] == 1]
}, index=[‘A’, ‘B’, ‘C’])