我想在不复制数据的情况下连接两个熊猫 DataFrame。也就是说,我希望连接的 DataFrame 是两个原始 DataFrame 中数据的视图。我尝试使用 concat() 并没有奏效。此代码块显示更改基础数据会影响连接的两个 DataFrame,但不会影响连接的 DataFrame:
arr = np.random.randn(12).reshape(6, 2)
df = pd.DataFrame(arr, columns = ('VALE5', 'PETR4'), index = dates)
arr2 = np.random.randn(12).reshape(6, 2)
df2 = pd.DataFrame(arr, columns = ('AMBV3', 'BBDC4'), index = dates)
df_concat = pd.concat(dict(A = df, B = df2),axis=1)
pp(df)
pp(df_concat)
arr[0, 0] = 9999999.99
pp(df)
pp(df_concat)
这是最后五行的输出。将新值分配给 arr[0, 0] 后,df 发生了变化;df_concat 不受影响。
In [56]: pp(df)
VALE5 PETR4
2013-01-01 -0.557180 0.170073
2013-01-02 -0.975797 0.763136
2013-01-03 -0.913254 1.042521
2013-01-04 -1.973013 -2.069460
2013-01-05 -1.259005 1.448442
2013-01-06 -0.323640 0.024857
In [57]: pp(df_concat)
A B
VALE5 PETR4 AMBV3 BBDC4
2013-01-01 -0.557180 0.170073 -0.557180 0.170073
2013-01-02 -0.975797 0.763136 -0.975797 0.763136
2013-01-03 -0.913254 1.042521 -0.913254 1.042521
2013-01-04 -1.973013 -2.069460 -1.973013 -2.069460
2013-01-05 -1.259005 1.448442 -1.259005 1.448442
2013-01-06 -0.323640 0.024857 -0.323640 0.024857
In [58]: arr[0, 0] = 9999999.99
In [59]: pp(df)
VALE5 PETR4
2013-01-01 9999999.990000 0.170073
2013-01-02 -0.975797 0.763136
2013-01-03 -0.913254 1.042521
2013-01-04 -1.973013 -2.069460
2013-01-05 -1.259005 1.448442
2013-01-06 -0.323640 0.024857
In [60]: pp(df_concat)
A B
VALE5 PETR4 AMBV3 BBDC4
2013-01-01 -0.557180 0.170073 -0.557180 0.170073
2013-01-02 -0.975797 0.763136 -0.975797 0.763136
2013-01-03 -0.913254 1.042521 -0.913254 1.042521
2013-01-04 -1.973013 -2.069460 -1.973013 -2.069460
2013-01-05 -1.259005 1.448442 -1.259005 1.448442
2013-01-06 -0.323640 0.024857 -0.323640 0.024857
我猜这意味着 concat() 创建了数据的副本。有没有办法避免复制?(我想尽量减少内存使用)。
此外,是否有一种快速的方法来检查两个 DataFrame 是否链接到相同的基础数据?(无需经历更改数据和检查每个 DataFrame 是否已更改的麻烦)
谢谢您的帮助。
FS