简体   繁体   English

如何用列值替换pandas数据框中的每个值?

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

If I have a Pandas data frame like this: 如果我有这样的Pandas数据框:

    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: 如何用列值替换每个值,以便得到像这样的pandas数据框:

    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 IIUC使用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 : 使用np.tile mask

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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