python - 使用 pandas 的列 View ?

标签 python numpy pandas scipy

是否可以在不进行复制的情况下创建 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/

相关文章:

python - 如何检查字符串是否包含列表中的单词

python - NotImplementedError : Cannot convert a symbolic Tensor (lstm_2/strided_slice:0) to a numpy array. T

python - numpy 查找矩阵行中所有数字对组合的乘积

python - 如何将数据集读入 pandas 并忽略列数不均匀的行

python - 如何在 Python 中提取网页的某些部分

python - 从一列和一行创建矩阵

python - Selenium 测试 - 无论如何都会打印所有内容

从序列内部正确转换为 ndarray 的 Numpy 可转换类?

python - reshape 表格 - 列中的条目变为新列

python - 根据 MultiIndex DataFrame 中的第一级列删除重复项