pandas 的 itterows 更新问题

itterows updating issues for pandas

我有一个数据集:

    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

我编写了以下代码来更改我的数据框

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

结果是

  mina
  sara
  travi
  caty
  el
  tom

我的问题是为什么打印第二行? 有什么办法可以解决吗?

检查 pandas 文档 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html

它说:

You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect.

这就是它发生的原因。 使用这样的东西:print('\n'.join(df.drop_duplicates(subset='id')[name]))

这是你需要的吗?

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