-3

Is there a way to subtract a constant value from the whole column?

If my dataframe is

enter image description here

I want to subtract 2.5 from column 1 so that it appears as

enter image description here

Also, is it possible to convert Date+Time into minutes?

Thank you!

aneroid
  • 12,983
  • 3
  • 36
  • 66
Sharon
  • 43
  • 1
  • 5
  • 1
    I think you got your pictures backwards. Also, what have you tried? – miradulo Oct 11 '17 at 13:46
  • To subtract constant value, I did df=df.sub(shift,axis='Distance) but it gave me invalid syntax – Sharon Oct 11 '17 at 13:49
  • Did you read what `df.sub` does? You want either [`Series.sub`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sub.html) or just `df['some_column'] - some_constant`. You might want to take a read over the [Pandas docs](https://pandas.pydata.org/pandas-docs/stable/10min.html). – miradulo Oct 11 '17 at 13:52
  • I tried this df['some_column'] - some_constant, and it works except i didnt know how to put that back into the dataframe. df=read_data df=df['Distance']-2.5 df.to_csv(filename) I know I am rewrting df so that it only exports the shifted Distance column. How do i not do that? and export the whole dataframe with the shifted Distance – Sharon Oct 11 '17 at 14:03
  • nvm i got it! Thank you – Sharon Oct 11 '17 at 14:19

2 Answers2

2

If df is your dataframe, simply use

df.Distance += 2.5

for adding a constant, or

df.Distance -= 2.5

for subtracting it.

(I'm not sure which one of them you want to do.)

MarianD
  • 13,096
  • 12
  • 42
  • 54
-3

using .apply is always a fast way to handle something like this

#data.csv is you data
import pandas as pd
df = pd.DataFrame.read_csv('data.csv')

#you want to perform this operation on column 1 that has a label 'A'
#make a function
def col_subtract(row):
    row['A'] = row['A'] - 2.5
    return row

#apply the function to the dataframe
df = df.apply(col_subtract, axis=1)

doc

note: you could also just pass it a lambda function, I just felt it was cleaner to make a formal user defined function with a name to emphasize what you're doing.

Kevin Frankola
  • 29
  • 1
  • 1
  • 5
  • 3
    __No!__. Using `apply` is always the _slow_ way to handle something like this. It doesn't even make sense in this context, you're doing the vectorized operation inside the `apply` anyways. – miradulo Oct 11 '17 at 14:22
  • I just used depth=df['Distance']-62.981. Then to add the depth column to the front of the table: df.insert(0,'Depth',depth) Thanks! Also any idea on the time manipulation to minute? – Sharon Oct 11 '17 at 14:31