0

I am trying to run the following code on a Pandas Database formed by three columns (timestamp, A, B). Occasionally, it could have as well a column named 'C' and I want to check if it exists to do some code: I would like to create a new column named 'result1' or 'result2', depending on whether 'C' exists or not, and do a division in this column. After that, I would like to drop all columns but the timestamp and the one with the result.

Unfortunately, it is not working and I can't find why (it is not even creating the new columns), could any of you please give me a hand?

if 'C' in data.columns:
  data['result1'] = data['C'] / data['A']
  data = data.drop(data.columns.difference(['timestamp', 'result1']), 1, inplace=True)
else:
  data['result2'] = data['B'] / data['A']
  data = data.drop(data.columns.difference(['timestamp', 'result2']), 1, inplace=True)
Sara.SP92
  • 83
  • 1
  • 9
  • 2
    drop with `inplace=True` returns None. So, don't assign it back to `data` – SeaBean Jul 22 '21 at 09:31
  • I removed the inplace=True and it works now, thank you!! – Sara.SP92 Jul 22 '21 at 09:43
  • 2
    `inplace=True` is not considered a good practice. It is being gradually deprecated from Pandas. So avoid using it. See also [this post](https://stackoverflow.com/a/60020384/15070697) for more information. – SeaBean Jul 22 '21 at 09:46

0 Answers0