3

Given the following data frame: import pandas as pd

d = pd.DataFrame({'a':[1,2,3],'b':[np.nan,5,6]})
d
    a   b
0   1   NaN
1   2   5.0
2   3   6.0

For any column where a value is 'NaN', I'd like to replace that value with the column name. My real data has many columns.

Desired result:

    a   b
0   1   b
1   2   5.0
2   3   6.0

Thanks in advance!

1 Answer 1

5

IIUC:

In [60]: d.fillna(d.columns.to_series())
Out[60]:
   a  b
0  1  b
1  2  5
2  3  6
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, will mark as correct once I can. As a follow-up, what if I wanted to instead fill any non-null value with the column name?
@DanceParty2, that's an nteresting question! Let me try to find a solution for it...
Sure. I'll post as a separate question and share the link.
Thanks. I've posted the question here: stackoverflow.com/questions/45825048/…
@DanceParty2, you've got already a very neat and elegant answer from root ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.