The Python Oracle

How to fill true values of a dataframe with column names?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 How To Fill True Values Of A Dataframe With Column Names?
00:26 Accepted Answer Score 5
00:59 Answer 2 Score 0
01:27 Thank you

--

Full question
https://stackoverflow.com/questions/4593...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #mask

#avk47



ACCEPTED ANSWER

Score 5


First replace booelan to int and then use mask or where with inverting mask by ~:

df = df.astype(int).mask(df, df.columns.to_series(), axis=1)
print (df)
   A  B  C  D
0  0  B  C  0
1  0  0  C  0
2  A  B  0  0

df = df.astype(int).where(~df, df.columns.to_series(), axis=1)
print (df)
   A  B  C  D
0  0  B  C  0
1  0  0  C  0
2  A  B  0  0

Thank you John Galt for improvement in new versions of pandas 0.21.x:

df = df.astype(int).mask(df, df.columns, axis=1)

numpy solution:

a = np.tile(df.columns, [len(df.index),1])
print (a)
[['A' 'B' 'C' 'D']
 ['A' 'B' 'C' 'D']
 ['A' 'B' 'C' 'D']]

df = pd.DataFrame(np.where(df.astype(int), a, 0), columns=df.columns, index = df.index)
print (df)
   A  B  C  D
0  0  B  C  0
1  0  0  C  0
2  A  B  0  0



ANSWER 2

Score 0


pandas 1.5.2

df = df.mask(df.astype(bool), df.columns.to_series(), axis=1)

not astype(int) but astype(bool) or astype('bool')

Otherwise ValueError: Boolean array expected for the condition, not uint8


can't remove .to_series()

Otherwise ValueError: other must be the same shape as self when an ndarray