Home > database >  Subtract value in Specific columns in CSV file
Subtract value in Specific columns in CSV file

Time:08-21

I would like to subtract a value example value 2 on a specific column of a data frame

csv1=

      X      Y     Subdie 1v 2v 5v 10v
  0   1      0       4    2   4 2  2
  1   2      0       2    3   4 4  6
  2   3      0       3    5   4 6  8 
  3   4      0       4    2   5 4  4
  4   5      0       4    2   5 8  4 

I want to subtract 2 on 1v and 2v columns, I tried with this code

Cv=(csv1.loc[:,' 1v':' 5v'])-2

I got an output like

    1v  2v  5v
 0  0   2   0
 1  1   2   2
 2  3   2   4 
 3  0   3   2
 4  0   3   6

Expected output: include other columns also

     x   y  1v  2v  5v  10v
0    1   0   0   2   0  2
1    2   0   1   2   2  6
2    3   0   3   2   4  8
3    4   0   0   3   2  4
4    5   0   0   3   6  4

CodePudding user response:

Don't create a copy, perform an in place modification:

csv1.loc[:, ' 1v':' 5v'] -= 2

modifiers csv1:

   X  Y  Subdie  1v  2v  5v  10v
0  1  0       4   0   2   0    2
1  2  0       2   1   2   2    6
2  3  0       3   3   2   4    8
3  4  0       4   0   3   2    4
4  5  0       4   0   3   6    4

NB. I kept your slice as in the question, but you should avoid having leading spaces in the column names. Also, ' 1v':' 5v' selects 1v, 2v, and 5v (included).

  • Related