Search code examples
pythonpandasdataframeadditionsubtraction

Python Pandas Adding or Subtracting User Defined Numbers to DataFrame


I am trying to modify a dataframe that i am reading from an excel. I want to modify the columns 'Region1' and 'Region2', more specifically i want to subtract a user-defined number from 'Region1' column and add a user-defined number to 'Region2'. Can i modify the dataframe so that i can do both operations at the same time, i.e. subtract 5 from 'Region1' and add 5 to 'Region2'.

import pandas as pd
import numpy as np

df = pd.read_csv('C:\\Users\\blahblah\\Desktop\\testroi.bed', delimiter= '\t')

df[['Region1', 'Region2']]

Region1 Region2
0   25870184    25870282
1   25880407    25880560
2   25881345    25881468
3   25883638    25883763
4   25889129    25889212
... ... ...
432 107645314   107645443
433 107646702   107646854
434 107651377   107651481
435 107651648   107651661
436 107665889   107665965
437 rows × 2 columns

I can create new dfs for 'Region1' and 'Region2' to do adding/subtracting, but i am wondering if i can perform this two operation at the same time with 1 line of code on the same dataframe. So basically using the dataframe above, 0th index would be 25870184 - 5 = 25870179 for 'Region1' and 25870282 + 5 = 25870287 for 'Region2'. Repeat the operation from all columns and rows, i.e. i know i can do via df=df['Region1'] -5 but i am wondering if i can do two operations at the same time i.e. df = df['Region1'] -5 , df['Region2'] + 5. The trouble i have is making two operations at the same time on the same data frame.

Thanks


Solution

  • The simplest (and fastest, as it is inplace) is:

    df[['Region1', 'Region2']] += [-5, 5]
    
    >>> df[['Region1', 'Region2']]
           Region1    Region2
    0     25870179   25870287
    1     25880402   25880565
    2     25881340   25881473
    3     25883633   25883768
    4     25889124   25889217
    432  107645309  107645448
    433  107646697  107646859
    434  107651372  107651486
    435  107651643  107651666
    436  107665884  107665970