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.
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.
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.
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.
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
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
You can also do this using the pandas.apply function
df.loc[:, "hb"] = df["hb"].apply(lambda x: x - 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With