Search code examples
python-3.xpandasgroup-by

Cell by cell addition of floats in two pandas dataframes by matching the row values of the first column


I have two Pandas dataframes containing floats with row values of the first column which differ slightly. For example,

df_1 = timestamps column_1 column_2 ... column_n
          row_1         
          row_2
          row_3
          row_4 
          row_5
          row_6
             .
             .
             .
             n

df_2 = timestamps column_1 column_2 ... column_n
          row_1         
          row_2
          row_3
          row_4 
          row_5
          row_7
             .
             .
             .
             n

As you can see, row_6 in df_1 is swapped with row_7 in df_2. Could someone please help me in adding the two dataframes cell by cell after aligned by identical row values of the first column. I want to do something like df_2 = df_1 + df_2 inside a for loop with a counter n. Finally, I want to do df_2 = df_2/n to give some more context.


Solution

  • if I understand correctly,

    df_1
    ###
      timestamp  column_1  column_2
    0        t1         1         6
    1        t2         2         7
    2        t3         3         8
    3        t4         4         9
    4        t5         5        10
    
    df_2
    ###
      timestamp  column_1  column_2
    0        t1        11        16
    1        t2        12        17
    2        t5        13        18
    3        t6        14        19
    4        t7        15        20
    



    Use iloc to deal with calculation,

    df_2.iloc[:, 1:] = df_1.iloc[:, 1:] + df_2.iloc[:, 1:]
    df_2
    ###
      timestamp  column_1  column_2
    0        t1        12        22
    1        t2        14        24
    2        t5        16        26
    3        t6        18        28
    4        t7        20        30