How to fill true values of a dataframe with column names?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Question
00:39 Accepted answer (Score 5)
01:23 Answer 2 (Score 0)
02:03 Thank you
--
Full question
https://stackoverflow.com/questions/4593...
Accepted answer links:
[mask]: http://pandas.pydata.org/pandas-docs/sta...
[where]: http://pandas.pydata.org/pandas-docs/sta...
[John Galt]: https://stackoverflow.com/questions/4593...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #mask
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Question
00:39 Accepted answer (Score 5)
01:23 Answer 2 (Score 0)
02:03 Thank you
--
Full question
https://stackoverflow.com/questions/4593...
Accepted answer links:
[mask]: http://pandas.pydata.org/pandas-docs/sta...
[where]: http://pandas.pydata.org/pandas-docs/sta...
[John Galt]: 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