3

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Diego
  • 392
  • 3
  • 16

2 Answers2

3

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
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Thanks for your response. This helps a lot. Out of curiosity, why does this update method fail when inplace is set to `True`? – Diego Jul 24 '20 at 19:35
  • 1
    @Diego because update is already `inplace` check documentation – anky Jul 24 '20 at 19:39
2

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
anky
  • 74,114
  • 11
  • 41
  • 70
  • This seems to do the trick, but I don't always need to update boolean values. Can you please explain why I would need a double asterisk here ? – Diego Jul 24 '20 at 19:36
  • 1
    @Diego since we are using as a `kwargs`: [this](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) might be a good read to clarify – anky Jul 24 '20 at 19:38