Setting values in DataFrames using .loc

Viewed 234

I have a configuration where it would be extremely useful to modify value of a dataframe using a combination of loc and iloc.

df = pd.DataFrame([[1,2],[1,3],[1,4],[2,6],[2,5],[2,7]],columns=['A','B'])

Basically in the dataframe above, I would like to take only the column that are equal to something (i.e. A = 2). which would give :

   A  B
3  2  6
4  2  5
5  2  7

And then modify the value of B of the second index (which is actually the index 4 in this case) I can access to the value I want using this command :

df.loc[df['A'] == 2,'B'].iat[1]

(or .iloc instead of .iat, but I heard that for changing a lot of single row, iat is faster)

It yields me : 5

However I cannot seems to be able to modify it using the same command :

df.loc[df['A'] == 2,'B'].iat[1] = 0 

It gives me :

   A  B
0  1  2
1  1  3
2  1  4
3  2  6
4  2  5
5  2  7

I would like to get this :

   A  B
0  1  2
1  1  3
2  1  4
3  2  6
4  2  0
5  2  7

Thank you !

2 Answers

We should not chain .loc and .iloc (iat,at)

df.loc[df.index[df.A==2][1],'B']=0
df
   A  B
0  1  2
1  1  3
2  1  4
3  2  6
4  2  0
5  2  7

You can go around with cumsum, which counts the instances:

s = df['A'].eq(2)

df.loc[s & s.cumsum().eq(2), 'B'] = 0

Output:

   A  B
0  1  2
1  1  3
2  1  4
3  2  6
4  2  0
5  2  7
Related