3

I have a DataFrame, df, with 3 columns and I want to perform subtraction as follows:

df['available'] = df['recommended'] - df['manual input']

But I am getting an error stating:

unsupported operand type(s) for -: 'int' and 'str'

I have also tried doing

df['available'] = df['recommended'].sub(df['manual input'])

but it shows the same error.

Also I would like to know that does it returns Series if we try to get particular column from dataframe??

ayhan
  • 70,170
  • 20
  • 182
  • 203
Rishikesh
  • 53
  • 1
  • 4
  • 1
    What do you expect to happen when you subtract a string from an int or vice versa? Unlike JS, they aren't coerced. – cs95 Jan 19 '18 at 10:45
  • 1
    `df['available'] = df['recommended'] - df['manual input'].astype(int)` ? – jezrael Jan 19 '18 at 10:45
  • 1
    It is, what the error message says. Inputs are strings, you have to convert them with `int()` or `float()`, before adding them to your dataframe. Alternatively, you can convert the data type of a column. [See for instance here](https://stackoverflow.com/questions/15891038/change-data-type-of-columns-in-pandas). But all of this are just guesses, since you didn't provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Mr. T Jan 19 '18 at 10:49
  • @COLDSPEED This helped out. Thankyou! – Rishikesh Jan 19 '18 at 12:24
  • Thankyou @Piinthesky – Rishikesh Jan 19 '18 at 12:24
  • jezrael provided a good example, if you want to perform the addition, but keep the string column. – Mr. T Jan 19 '18 at 12:32
  • @jezrael it worked completely fine for me. Thanks alot – Rishikesh Jan 19 '18 at 15:28
  • @Rishikesh - you are welcome! – jezrael Jan 19 '18 at 15:29

2 Answers2

4

You have to convert values to numeric - e.g. to integers:

df['available'] = df['recommended'] - df['manual input'].astype(int)

Or to floats:

df['available'] = df['recommended'] - df['manual input'].astype(float)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
-2

df['available'] = df['recommended'].values - df['manual input'].values