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

Time:12-12

I want to update the first row of a dataframe that meets a certain condition. Like in this question Get first row of dataframe in Python Pandas based on criteria but for setting instead of just selecting.

df[df['Qty'] > 0].iloc[0] = 5 

The above line does not seem to do anything.

CodePudding user response:

I believe what you're looking for is:

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

CodePudding user response:

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
  • Related