Python熊猫使用.iloc

时间:2019-04-29 21:45:17

标签: python pandas

我有数据框

a=pd.DataFrame([[1,1,9],[2,1,9],[3,2,9],[4,2,9]],columns=['a','b','c'])

   a  b  c
0  1  1  9
1  2  1  9
2  3  2  9
3  4  2  9

如果我运行

a['c'].iloc[0]=100

它起作用了,我明白了

   a  b    c
0  1  1  100
1  2  1    9
2  3  2    9
3  4  2    9

但是如果我想通过运行来更新组b == 2的第一个观察结果

a['c'][a['b']==2].iloc[0]=100

它不执行我想要的操作。我仍然得到相同的数据框。

   a  b    c
0  1  1  100
1  2  1    9
2  3  2    9
3  4  2    9

我想知道为什么吗?对此有什么可能的解决方案?

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您应该像这样使用.loc,有时.iloc.loc会引起issue

 Whether a copy or a reference is returned for a setting operation, may depend on the context. This is sometimes called chained> assignment and should be avoided
a.loc[a.index[a.b==2][0],'c']=10000
a
Out[761]: 
   a  b      c
0  1  1      9
1  2  1      9
2  3  2  10000
3  4  2      9
相关问题