简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM