是否可以在不进行复制的情况下创建 pandas 列中的值的 View ?一个例子:
import numpy as np
import pandas as pd
class Aclass:
pass
df = pd.DataFrame(np.random.rand(8,2),columns=['a','b'])
这有效:
Aclass.a = df['a']
Aclass.a is df['a']
Out[51]: True
但不是这个:
Aclass.a = df['a'].values
Aclass.a is df['a'].values
Out[54]: False
我想以此作为一种将 pandas 逐步包含到项目中的方法,而不会受到过多额外内存使用的影响。
最佳答案
实际上,在这种情况下,您没有复制数据,只是复制数组“容器”。
在很多情况下,df.values
将返回副本(例如,不同列的不同数据类型或数据在内存中不连续的任何情况),但对于简单的系列或具有一种数据类型的 DataFrame,它返回数据的 View 。
即使数组对象不同,它们也指向相同的数据缓冲区。仅使用了一些额外字节的内存。
例如:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(8,2),columns=['a','b'])
# Every time you call `values` a new array object is created:
print df.a.values is df.a.values # This will be False
# But the data is _not_ copied:
x = df['a'].values
y = df.a.values
print np.may_share_memory(x, y) #This will be True
# And if we modify "x" or "y", we'll modify the original data frame:
x[0] = -9
y[-1] = -8
print df
# However, this only holds for cases where the data can be
# viewed as a numpy array.
# This will modify the original dataframe:
z = df.values
z[0,:] = -5
print df
# But this won't, because the types are different and "values" returns
# a copy:
df['b'] = df['b'].astype(int)
arr = df.values
arr[0,:] = 10
print df
关于python - 使用 pandas 的列 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587377/