在Pandas中,.iloc方法是否提供副本或视图?

2024-05-29 11:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现结果有点随机。有时是复制品有时是风景。例如:

df = pd.DataFrame([{'name':'Marry', 'age':21},{'name':'John','age':24}],index=['student1','student2'])

df
              age   name
   student1   21  Marry
   student2   24   John

现在,让我试着修改一下。

df2= df.loc['student1']
df2 [0] = 23
df
              age   name
   student1   21  Marry
   student2   24   John

如你所见,一切都没有改变。df2是副本。但是,如果我在数据框中添加另一个学生。。。

df.loc['student3'] = ['old','Tom']
df
               age   name
    student1   21  Marry
    student2   24   John
    student3  old    Tom

再次尝试更改年龄。。

df3=df.loc['student1']
df3[0]=33
df
               age   name
    student1   33  Marry
    student2   24   John
    student3  old    Tom

现在df3突然变成了一个视图。怎么回事?我想“旧”的价值才是关键?


Tags: namedfagejohnoldlocdf2tom

热门问题