我有下面的代码,然后有我的代码输出。有人知道为什么a,b,c变量不保持其值吗?
import pandas as pd
df = pd.DataFrame(columns=['A', 'B', 'C'])
for i in range(3):
df.loc[0] = [i, i, i]
if i == 0:
a = df
print "Printing a inside of the loop:"
print a
elif i == 1:
b = df
print "Printing b inside of the loop:"
print b
elif i == 2:
c = df
print "Printing c inside of the loop:"
print c
print "Printing a outside of the loop:"
print a
print "Printing b outside of the loop:"
print b
print "Printing c outside of the loop:"
print c
答案 0 :(得分:2)
您的问题是a,b,c
实际上不是单独的变量。
Python的内部工作方式意味着为什么您说a = df
,Python对df
进行了引用,所以a
实际上指向与df
相同的基础内存-基本上,它只是同一变量的另一个名称。
这意味着您在这里所做的是为循环的每次迭代覆盖df
中的数字,然后在您读回a
,b
和{{ 1}},您只是在读取c
中的数据。
您实际需要的是使用(例如)df
的数据帧的真实副本。