pandas:使用 where 更新多列

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

我正在尝试使用Python中的mask一次更新多个列pandas

我想将以下两个能够正确执行的连续语句组合成一个语句

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'])
以上两条语句更新两列(称为 

ModelManufacturer)中的值,并将它们分别设置为存储为 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 错误 KeyError: ('Model', 'Manufacturer')

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

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.