将列表传递给 pandas loc 方法

Passing a list to pandas loc method

我想更改 pandas 数据框中某些列的值。但是如果我在 loc.

中传递列列表,我似乎做不到
df = pd.DataFrame({
"ID" : [1, 2, 3, 4, 5],
"QA_needed" : [0, 1, 1, 0, 1],
"QC_needed" : [1, 0, 1, 0, 0],
"Report_needed" : [1, 1, 1, 0, 1]
})

df.loc[:, ["QA_needed", "Report_needed"]].replace({1: "True", 0: "False"}, inplace=True)

为此,我必须单独替换每一列的值

df.loc[:, "QA_needed"].replace({1: "True", 0: "False"}, inplace=True)
df.loc[:, "QC_needed"].replace({1: "True", 0: "False"}, inplace=True)

有没有办法将列表 ["QA_needed", "Report_needed"] 传递给 loc 方法?

尝试update

df.update(df.loc[:, ["QA_needed", "Report_needed"]].replace({1: "True", 0: "False"}))
df
Out[96]: 
   ID QA_needed  QC_needed Report_needed
0   1     False          1          True
1   2      True          0          True
2   3      True          1          True
3   4     False          0         False
4   5      True          0          True

您还可以分配一个布尔值(bool):

df = df.assign(**df[['QA_needed','Report_needed']].astype(bool))

   ID  QA_needed  QC_needed  Report_needed
0   1      False          1           True
1   2       True          0           True
2   3       True          1           True
3   4      False          0          False
4   5       True          0           True