熊猫数据框仅将最后一个值保留在for循环中

时间:2020-02-10 19:24:07

标签: python pandas dataframe

我有下面的代码,然后有我的代码输出。有人知道为什么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

代码输出: enter image description here

1 个答案:

答案 0 :(得分:2)

您的问题是a,b,c实际上不是单独的变量。

Python的内部工作方式意味着为什么您说a = df,Python对df进行了引用,所以a实际上指向与df相同的基础内存-基本上,它只是同一变量的另一个名称。

这意味着您在这里所做的是为循环的每次迭代覆盖df中的数字,然后在您读回ab和{{ 1}},您只是在读取c中的数据。

您实际需要的是使用(例如)df的数据帧的真实副本。