我有以下数据框:
df:
A B_x B_y C_x C_y
R1 0 3 6 7
R2 NAN 4 8 9
R3 2 5 NAN 2
我希望将 _x 列中的 NAN 值替换为相应的 _y 列。
我不能使用像 B_x 和 B_y 这样的绝对名称,因为列名称是从以前的代码动态派生的,我无法控制它。
现在我正在使用以下内容:
ens_prefix is a variable which holds values of column along with _x
ens_prefix_1 is a variable which holds values of column along with _y
df[ens_prefix].fillna(df[ens_prefix_1], inplace=True) # replace values of NAN from _x column with _y
df = df.filter(regex=r'.*(?<!_y)$') # remove columns with _y suffix
df.columns = df.columns.str.rstrip('_x') # strip suffix at the right end only.
预期输出:
A B C
0 R1 0.0 6.0
1 R2 4.0 8.0
2 R3 2.0 2.0
最佳答案
首先,我更喜欢在列名称中使用 replace
而不是 strip
,因为 strip
也应该删除所有最后的 x
, y
值不仅在 _
之后,而且在 _
之前。
解决方案使用DataFrame.fillna
将 _x
替换为空字符串,并在最后一步中选择最后一个 _y
并删除 _y
列:
df = (df.rename(columns = lambda x: x.replace('_x', ''))
.fillna(df.filter(regex='_y$')
.rename(columns = lambda x: x.replace('_y', '')))
.filter(regex=r'.*(?<!_y)$'))
print (df)
A B C
0 R1 0.0 6.0
1 R2 4.0 8.0
2 R3 2.0 2.0
关于python 列替换和 fillnna,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62187172/