Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substract a single value from column of pandas DataFrame

Tags:

python

pandas

i have one data frame suppose:

name age hb
ali  34  14
jex  16  13
aja  24  16
joy  23  12

i have a value say "5" that i want to substract from each member of column "hb"

new column could be:

hb
9
8
11
7

What is the best method to do this...

thanks and regards.

like image 424
jax Avatar asked Oct 15 '15 05:10

jax


People also ask

How do I remove a value from a column in pandas?

Use drop() method to delete rows based on column value in pandas DataFrame, as part of the data cleansing, you would be required to drop rows from the DataFrame when a column value matches with a static value or on another column value.

How do you subtract values in pandas?

Pandas DataFrame sub() MethodThe sub() method subtracts each value in the DataFrame with a specified value. The specified value must be an object that can be subtracted from the values in the DataFrame.

How do you subtract a value from a DataFrame in Python?

subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentially same as doing dataframe – other but with a support to substitute for missing data in one of the inputs.


3 Answers

Simply subtract the scalar value from the pandas.Series , for numerical columns pandas would automatically broadcast the scalar value and subtract it from each element in the column. Example -

df['hb'] - 5 #Where `df` is your dataframe. 

Demo -

In [43]: df Out[43]:   name  age  hb 0  ali   34  14 1  jex   16  13 2  aja   24  16 3  joy   23  12  In [44]: df['hb'] - 5 Out[44]: 0     9 1     8 2    11 3     7 Name: hb, dtype: int64 
like image 200
Anand S Kumar Avatar answered Oct 01 '22 06:10

Anand S Kumar


If you are using this:

df['hb'] - 5

you will get a new single column. But if you want to keep the rest then you have to use:

df['hb'] -= 5
like image 37
Durmus Avatar answered Oct 01 '22 05:10

Durmus


You can also do this using the pandas.apply function

df.loc[:, "hb"] = df["hb"].apply(lambda x: x - 5)

like image 34
Colin Anthony Avatar answered Oct 01 '22 05:10

Colin Anthony