Home > Software design >  Subtraction in dataframe between rows
Subtraction in dataframe between rows

Time:06-24

i want an easy subtraction of two values. I want to replace the value in [10, 150] by calculation the value in ([10, 150] - [9, 150]). Somehow the code does not like the "rows-1"

  for columns in listofcolumns:
        rows = 0
        while rows < row_count:
            column= all_columns.index(columns)
            df_merged.iloc[rows, column] = (df_merged.iloc[rows, column] - df_merged.iloc[rows-1, columns])
            rows = rows  1

It seems to be the case that the df_merged.iloc[rows-1, column] takes the last value of the column. I used the exact same line in another script before and it worked

This would be an example of some columns

  Col1        Col2        
  0            2
  0            3 
  0            4
  0            4
  1            5
  1            7
  1            8
  1            8 
  2            8 

The output dataframe i want would look like this.

  Col1        Col1        
  nAn          nAn
  0            1 
  0            1
  0            0
  1            1
  0            2
  0            1
  0            1 
  1            1 

CodePudding user response:

If I understood what you want to do, this would be the solution:

data = {'A': [5,7,9,3,2], 'B': [1,4,6,1,2]}
df = pd.DataFrame(data)
df["A"] = df["A"] - df["B"]
DataFrame at the start
   A  B
0  5  1
1  7  4
2  9  6
3  3  1
4  2  2
DataFrame at the end
   A  B
0  4  1
1  3  4
2  3  6
3  2  1
4  0  2

CodePudding user response:

Seems like you want to subtract previous row's values from each row. diff should help you.

df.diff()
  • Related