Diego
Diego

Reputation: 422

Passing a list to pandas loc method

I'd like to change the values of certain columns in a pandas dataframe. But I can't seem to do if I pass a list of columns inside 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)

To do this I have to replace the values for each column individually

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

Is there a way to pass the list ["QA_needed", "Report_needed"] to the loc method?

Upvotes: 3

Views: 3006

Answers (2)

anky
anky

Reputation: 75080

You can also assign a boolean(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

Upvotes: 2

BENY
BENY

Reputation: 323246

Try 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

Upvotes: 3

Related Questions