1

Imagine we have dataframe and let's try to filter it like:

df[df[0] == 'Test_value'].iloc[:, 1:5] 

So that we have filtered by values Test_value in a column 0, and we take only 1 to 5 columns. Now I want to change these values from dataframe. I want to multiply them by a list like [1,3,1,2].

At the end, I want my initial dataframe with changes only in those specific cells.

ps: df.mul() func doing well but it's only return me changed cells (df[df[0] == 'Test_value].iloc[:, 1:5]), but I cannot set them to my initial dataframe: df[df[0] == 'Test_value].iloc[:, 1:5] = df[df[0] == 'Test_value].iloc[:, 1:5].mul(list) not working ((

shyamzzp
  • 115
  • 7

1 Answers1

0

Problem is with chain indexing, possible solution is filter by DataFrame.iloc only with convert boolean mask to numpy array by Series.to_numpy:

df = pd.DataFrame({
        0:['Test_value'] *6,
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':[5,3,6,9,2,4],
})

dont use variable list because builtins
L = [1,3,1,2]
#pandas 0.24+
df.iloc[(df[0] == 'Test_value').to_numpy(), 1:5] *= L
#pandas below
#df.iloc[(df[0] == 'Test_value').values, 1:5] *= L
print (df)

            0  B   C  D   E  F
0  Test_value  4  21  1  10  5
1  Test_value  5  24  3   6  3
2  Test_value  4  27  5  12  6
3  Test_value  5  12  7  18  9
4  Test_value  5   6  1   4  2
5  Test_value  4   9  0   8  4
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252