Search code examples
pythonpandaspandas-loc

itterows updating issues for pandas


I have a dataset:

    id   name  m
0   1    mina  0
1   1    sara  0
2   2    travi 0
3   3    caty  0
5   4    el    0
6   6    tom   0

I wrote the following code for changing my dataframe

for index, row in df.iterrows():
     if(row['m']==0):
          df.loc[df['id'] ==row['id'] ,'m'] = 1
      print(row['name'])

and the result is

  mina
  sara
  travi
  caty
  el
  tom

my question is why the second row is printed? Is there any way to solve it?


Solution

  • Is that what you need?

    for item in df['id']:
          if ((df.loc[df['id'] == item, 'm'].values[0]) == 0):
                df.loc[df['id'] == item, 'm'] = 1  
           print(item)