Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

python - How to replace a value in a pandas dataframe with column name based on a condition?

I have a dataframe that looks something like this:

enter image description here

I want to replace all 1's in the range A:D with the name of the column, so that the final result should resemble:

enter image description here

How can I do that?

You can recreate my dataframe with this:

dfz = pd.DataFrame({'A' : [1,0,0,1,0,0],
                    'B' : [1,0,0,1,0,1],
                    'C' : [1,0,0,1,3,1],
                    'D' : [1,0,0,1,0,0],
                    'E' : [22.0,15.0,None,10.,None,557.0]})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way could be to use replace and pass in a Series mapping column labels to values (those same labels in this case):

>>> dfz.loc[:, 'A':'D'].replace(1, pd.Series(dfz.columns, dfz.columns))
   A  B  C  D
0  A  B  C  D
1  0  0  0  0
2  0  0  0  0
3  A  B  C  D
4  0  0  3  0
5  0  B  C  0

To make the change permanent, you'd assign the returned DataFrame back to dfz.loc[:, 'A':'D'].

Solutions aside, it's useful to keep in mind that you may lose a lot of performance benefits when you mix numeric and string types in columns, as pandas is forced to use the generic 'object' dtype to hold the values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...