python 列替换和 fillnna

标签 python pandas dataframe

我有以下数据框:

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/

相关文章:

Python追加到列表中的字符串元素

python - 在字典上迭代列表以映射项目

python - 在 groupby 中使用 sort_values 和 inplace=True 时到底出了什么问题?

python - VS代码无法导入已安装的模块

python - 使用 Pandas 查找两个不同大小的数据帧之间的不同行

r - 将一个小的随机样本从一个大的 csv 文件加载到 R 数据框中

javascript - 为什么 Django admin "Today"和 "Now"按钮不显示在 Safari 中?

python - 如何从控制台运行 twisted?

r - 按顺序对数据框中的一系列行应用匹配和替换函数

dataframe - 如何通过使用嵌套属性创建的Elasticsearch索引解决Root映射定义的参数不受支持的问题?