The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5

--

Chapters
00:00 How To Fill True Values Of A Dataframe With Column Names?
00:29 Accepted Answer Score 5
01:11 Answer 2 Score 0
01:45 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