使用来自 pandas 的列视图?

Using a view of columns from pandas?

是否可以在不制作副本的情况下创建 pandas 列中值的视图?一个例子:

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 包含到项目中,而不会因过多的额外内存使用而受到影响。

实际上,在这种情况下,您并不是在复制数据,只是复制数组 "container"。

很多情况下 df.values 会 return 一个副本(例如,不同列的不同数据类型或数据在内存中不连续的任何情况),但对于一个简单的series 或具有一种数据类型的 DataFrame,它 return 是数据的视图。

即使数组对象不同,它们指向同一个数据缓冲区。只使用了几个额外的内存字节。

例如:

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