如何在单个语句中使用 where 更新多个列?

问题描述 投票:0回答:1

我想将两个语句合并为一个:

inspections_df["Model"] = inspections_df["Model"].mask(
    inspections_df['Boiler Model'].str.contains(
        product['search for'], na=False, case=False), product['name'])

inspections_df["Manufacturer"] = inspections_df["Manufacturer"].mask(
    inspections_df['Boiler Model'].str.contains(
        product['search for'], na=False, case=False), manufacturer['manufacturer name'])

它们将

Model
Manufacturer
列中的值更新为存储为
product['name']
manufacturer['manufacturer name']
的常量值,其中
Boiler Model
列与存储在
product['search for']
中的正则表达式匹配。我怎样才能把它写成一个单独的语句,为什么我的下面的不起作用?

inspections_df["Model", "Manufacturer"] = inspections_df["Model", "Manufacturer"].mask(
    inspections_df['Boiler Model'].str.contains(
        product['search for'], na=False, case=False), [product['name'], manufacturer['manufacturer name']])

我的尝试结果是:

KeyError:('型号','制造商')

紧接着

inspections_df["Model", "Manufacturer"]
引用
=

python pandas dataframe
1个回答
0
投票

错误 KeyError: ('Model', 'Manufacturer') 是 pandas DataFrame 不支持以

df["col1", "col2"]
方式进行多列索引的直接结果。相反,您应该使用
df[["col1", "col2"]]

但即使在更正列索引之后,您仍将面临另一个问题。方法

mask
不能直接用于更新多列。相反,您必须将该过程分解为两个步骤,但您仍然可以使用
numpy.where()
的帮助在一行代码中完成它。以下是具体操作方法:

import numpy as np

mask = inspections_df['Boiler Model'].str.contains(product['search for'], na=False, case=False)

inspections_df["Model"], inspections_df["Manufacturer"] = np.where(mask, (product['name'], manufacturer['manufacturer name']), (inspections_df["Model"], inspections_df["Manufacturer"]))

请注意,这行代码仅在

inspections_df["Model"]
inspections_df["Manufacturer"]
的大小相同时才有效。

这行代码使用掩码来查找应用于 ['Boiler Model'] 列的条件在哪里为真,如果为真,它将 ["Model"] 和 ["Manufacturer"] 的值替换为分别为新值

product['name']
manufacturer['manufacturer name']
,如果为 false,则保留旧值。

© www.soinside.com 2019 - 2024. All rights reserved.