Reputation: 816
If I have a Pandas data frame like this:
0 20 30 40 50
1 5 NaN 3 5 NaN
2 2 3 4 NaN 4
3 6 1 3 1 NaN
How do I replace each value with its column value such that I get a pandas data frame like this:
0 20 30 40 50
1 0 NaN 30 40 NaN
2 0 20 30 NaN 50
3 0 20 30 40 NaN
Upvotes: 3
Views: 66
Reputation: 164773
df = df.mask(df.notnull(), np.tile(df.columns, (df.shape[0], 1)))
print(df)
0 20 30 40 50
1 0 NaN 30 40.0 NaN
2 0 20.0 30 NaN 50.0
3 0 20.0 30 40.0 NaN
This assumes your column labels are integers; if not, first use:
df.columns = df.columns.astype(int)
Upvotes: 2
Reputation: 323326
IIUC using mul
df.notnull().mul(df.columns,1).replace('',np.nan)
0 20 30 40 50
1 0 NaN 30 40 NaN
2 0 20 30 NaN 50
3 0 20 30 40 NaN
Upvotes: 2