How to set value of first row of pandas dataframe meeting condition?

Viewed 1589
2 Answers

Given df below:

   a  b
0  1  2
1  2  1
2  3  1

you change the values in the first row where the value in column b is equal to 1 by:

df.loc[df[df['b'] == 1].index[0]] = 1000

Output:

      a     b
0     1     2
1  1000  1000
2     3     1

If you want to change the value in a specific column(s), you can do that too:

df.loc[df[df['b'] == 1].index[0],'a'] = 1000

      a  b
0     1  2
1  1000  1
2     3  1

I believe what you're looking for is:

idx = df[df['Qty'] > 0].index[0]
df.loc[[idx], ['Qty']] = 5

Related