Zmann3000
Zmann3000

Reputation: 816

How to replace each value in pandas data frame with column value?

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

Answers (2)

jpp
jpp

Reputation: 164773

Using mask with np.tile:

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

BENY
BENY

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

Related Questions