Dance Party2
Dance Party2

Reputation: 7536

Pandas Replace Null With Column Name

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!

Upvotes: 3

Views: 1306

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210872

IIUC:

In [60]: d.fillna(d.columns.to_series())
Out[60]:
   a  b
0  1  b
1  2  5
2  3  6

Upvotes: 5

Related Questions