简体   繁体   中英

Setting values in DataFrames using .loc

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 (ie 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 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM