Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map the headers to columns in pandas?

Tags:

python

pandas

I have a dataframe like :

A    B    C 
1    0    0
1    1    0
0    1    0
0    0    1

I want to have :

 A    B    C  label
 1    0    0   A
 1    1    0   AB
 0    1    0   B
 0    0    1   C

I've tried to do by map or apply but I couldn't figured it out.

like image 313
sunny Avatar asked Sep 12 '17 22:09

sunny


1 Answers

df = df.assign(label=[''.join([df.columns[n] for n, bool in enumerate(row) if bool]) 
                      for _, row in df.iterrows()])
>>> df
   A  B  C label
0  1  0  0     A
1  1  1  0    AB
2  0  1  0     B
3  0  0  1     C

Timings

# Set-up:
df_ = pd.concat([df] * 10000)

%%timeit
# Solution by @Wen 
df1 = df_.reset_index().melt('index')
df1 = df1[df1.value==1]
df['label'] = df1.groupby('index').variable.sum()
# 10 loops, best of 3: 47.6 ms per loop

%%timeit
# Solution by @MaxU
df_['label'] = df_.apply(lambda x: ''.join(df_.columns[x.astype(bool)].tolist()), axis=1)
# 1 loop, best of 3: 4.99 s per loop

%%timeit
# Solution by @TedPetrou
df_['label'] = np.where(df_, df_.columns, '').sum(axis=1)
# 100 loops, best of 3: 12.5 ms per loop

%%timeit
# Solution by @Alexander
df_['label'] = [''.join([df_.columns[n] for n, bool in enumerate(row) if bool]) for _, row in df_.iterrows()]
# 1 loop, best of 3: 3.75 s per loop

%%time
# Solution by @PiRSquared
df_['label'] = df_.dot(df_.columns)
# CPU times: user 18.1 ms, sys: 706 µs, total: 18.8 ms
# Wall time: 18.9 ms
like image 181
Alexander Avatar answered Oct 07 '22 11:10

Alexander