75_pandas.DataFrame 中查看和复制
75_pandas.DataFrame 中查看和复制
与pandas的DataFrame与NumPy数组ndarray类似,也有视图(view)和拷贝(copy)。
当使用loc[]或iloc[]等选择DataFrame的一部分以生成新的DataFrame时,与原对象共享内存的对象称为视图,与原对象分开重新分配内存的对象称为拷贝。
由于视图引用的是共同的内存,因此当一个对象的元素值被修改时,另一个对象的值也会被修改。
目录
- pandas.DataFrame的视图和拷贝的注意事项
- 通过loc, iloc进行部分选择
- 所有列数据类型dtype相同时
- 存在不同数据类型dtype的列时
- numpy.ndarray与pandas.DataFrame之间的内存共享
- 从numpy.ndarray生成pandas.DataFrame
- 从pandas.DataFrame生成numpy.ndarray
本文的示例代码中使用的pandas和NumPy版本如下。注意,由于版本不同,可能会有不同的规格。
import pandas as pd
import numpy as npprint(pd.__version__)
# 2.1.4print(np.__version__)
# 1.26.2
pandas.DataFrame的视图和拷贝的注意事项
关于DataFrame中的视图和拷贝,首先需要了解的是,至少在版本2.1.4的情况下,没有办法可以确定一个DataFrame是另一个DataFrame的视图还是拷贝。
如下面的例子所示,np.shares_memory()和DataFrame的_is_view属性也不能保证返回确定的结果。
通过调用DataFrame的copy()方法可以确保生成一个拷贝,但没有方法可以确保生成一个视图。在可能处理各种数据的代码中以视图为前提是危险的。
接下来会展示几个例子,但本文想要传达的不是“在这种情况下会返回视图(或拷贝)”,而是“无法确定会返回视图还是拷贝,所以要注意”。
通过loc, iloc进行部分选择
loc[]可以通过行名和列名选择DataFrame的范围,iloc[]可以通过行号和列号选择。不仅可以指定标量值,还可以使用切片或列表等指定多行多列。
- 04_Pandas获取和修改任意位置的值(at,iat,loc,iloc)
显示所有列数据类型dtype相同和存在不同数据类型dtype的列时的结果。
在几种模式下选择范围以生成新的DataFrame,显示np.shares_memory()和_is_view属性的结果,最后修改原DataFrame的元素值,以确认生成的DataFrame的值是否也被修改(是否共享内存)。
再重复一下,下面的示例代码和结果仅仅是一个例子,不能保证在所有条件下都生成视图或拷贝。
所有列数据类型dtype相同时
所有列数据类型dtype相同的情况。
df_homo = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]})
print(df_homo)
# A B
# 0 0 3
# 1 1 4
# 2 2 5print(df_homo.dtypes)
# A int64
# B int64
# dtype: object
通过切片选择。
df_homo_slice = df_homo.iloc[:2]
print(df_homo_slice)
# A B
# 0 0 3
# 1 1 4print(np.shares_memory(df_homo, df_homo_slice))
# Trueprint(df_homo_slice._is_view)
# True
通过列表选择。同样可以使用元组、ndarray、Series等指定。
df_homo_list = df_homo.iloc[[0, 1]]
print(df_homo_list)
# A B
# 0 0 3
# 1 1 4print(np.shares_memory(df_homo, df_homo_list))
# Falseprint(df_homo_list._is_view)
# False
布尔索引。同样可以使用元组、ndarray、Series等指定。
df_homo_bool = df_homo.loc[[True, False, True]]
print(df_homo_bool)
# A B
# 0 0 3
# 2 2 5print(np.shares_memory(df_homo, df_homo_bool))
# Falseprint(df_homo_bool._is_view)
# False
通过标量值选择。这种情况下是Series而非DataFrame。
s_homo_scalar = df_homo.iloc[0]
print(s_homo_scalar)
# A 0
# B 3
# Name: 0, dtype: int64print(np.shares_memory(df_homo, s_homo_scalar))
# Trueprint(s_homo_scalar._is_view)
# True
不使用loc[]或iloc[],而是用[列名]指定。
s_homo_col = df_homo['A']
print(s_homo_col)
# 0 0
# 1 1
# 2 2
# Name: A, dtype: int64print(np.shares_memory(df_homo, s_homo_col))
# Trueprint(s_homo_col._is_view)
# True
通过列表指定多个列名。
df_homo_col_list = df_homo[['A', 'B']]
print(df_homo_col_list)
# A B
# 0 0 3
# 1 1 4
# 2 2 5print(np.shares_memory(df_homo, df_homo_col_list))
# Falseprint(df_homo_col_list._is_view)
# False
修改原DataFrame的元素值,确认生成的DataFrame的值是否发生变化。
df_homo.iat[0, 0] = 100
print(df_homo)
# A B
# 0 100 3
# 1 1 4
# 2 2 5print(df_homo_slice)
# A B
# 0 100 3
# 1 1 4print(df_homo_list)
# A B
# 0 0 3
# 1 1 4print(df_homo_bool)
# A B
# 0 0 3
# 2 2 5print(s_homo_scalar)
# A 100
# B 3
# Name: 0, dtype: int64print(s_homo_col)
# 0 100
# 1 1
# 2 2
# Name: A, dtype: int64print(df_homo_col_list)
# A B
# 0 0 3
# 1 1 4
# 2 2 5
在这个简单的例子中,结果与np.shares_memory()和_is_view属性一致。
在列表和布尔索引中指定时,会生成拷贝,其他情况下则为视图。
需要注意的是,上述例子中仅指定了行[:2],但如果同时指定行和列(如[:2, [0, 1]]),只要行或列中包含列表,就会生成拷贝。另外,[0]是视图,而[[0]](包含一个元素的列表)是拷贝。
存在不同数据类型dtype的列时
存在不同数据类型dtype的列时比较复杂。以下Stack Overflow的回答中指出总是返回拷贝,但似乎也有例外。
以下是一个DataFrame的例子。
df_hetero = pd.DataFrame({'A': [0, 1, 2], 'B': ['x', 'y', 'z']})
print(df_hetero)
# A B
# 0 0 x
# 1 1 y
# 2 2 zprint(df_hetero.dtypes)
# A int64
# B object
# dtype: object
通过切片选择。仅行和行列都选择两种情况。
df_hetero_slice_row = df_hetero.iloc[:2]print(df_hetero_slice_row)
# A B# 0 0 x# 1 1 yprint(np.shares_memory(df_hetero, df_hetero_slice_row))# Falseprint(df_hetero_slice_row._is_view)# Falsedf_hetero_slice_row_col = df_hetero.iloc[:2, 0:]print(df_hetero_slice_row_col)# A B# 0 0 x# 1 1 yprint(np.shares_memory(df_hetero, df_hetero_slice_row_col))# Falseprint(df_hetero_slice_row_col._is_view)# False
通过列表选择。
df_hetero_list = df_hetero.iloc[[0, 1]]print(df_hetero_list)# A B# 0 0 x# 1 1 yprint(np.shares_memory(df_hetero, df_hetero_list))# Falseprint(df_hetero_list._is_view)# False
布尔索引。
df_hetero_bool = df_hetero.loc[[True, False, True]]print(df_hetero_bool)# A B# 0 0 x# 2 2 zprint(df_hetero_bool._is_view)# Falseprint(df_hetero_bool._is_view)# False
通过标量值选择。
s_hetero_scalar = df_hetero.iloc[0]print(s_hetero_scalar)# A 0# B x# Name: 0, dtype: objectprint(np.shares_memory(df_hetero, s_hetero_scalar))# Falseprint(s_hetero_scalar._is_view)# False
不使用loc[]或iloc[],而是用[列名]指定。
s_hetero_col = df_hetero['A']print(s_hetero_col)# 0 0# 1 1# 2 2# Name: A, dtype: int64print(np.shares_memory(df_hetero, s_hetero_col))# Falseprint(s_hetero_col._is_view)# True
通过列表指定多个列名。
df_hetero_col_list = df_hetero[['A', 'B']]print(df_hetero_col_list)# A B# 0 0 x# 1 1 y# 2 2 zprint(np.shares_memory(df_hetero, df_hetero_col_list))# Falseprint(df_hetero_col_list._is_view)# False
更改原DataFrame的元素值,确认生成的DataFrame的值是否改变。
df_hetero.iat[0, 0] = 100print(df_hetero)# A B# 0 100 x# 1 1 y# 2 2 zprint(df_hetero_slice_row)# A B# 0 100 x# 1 1 yprint(df_hetero_slice_row_col)# A B# 0 0 x# 1 1 yprint(df_hetero_list)# A B# 0 0 x# 1 1 yprint(df_hetero_bool)# A B# 0 0 x# 2 2 zprint(s_hetero_scalar)# A 0# B x# Name: 0, dtype: objectprint(s_hetero_col)# 0 100# 1 1# 2 2# Name: A, dtype: int64print(df_hetero_col_list)# A B# 0 0 x# 1 1 y# 2 2 z
仅按行切片选择时,np.shares_memory()和_is_view属性为False,但内存共享(原DataFrame的更改会反映)。
此外,用[列名]指定时,np.shares_memory()为False且_is_view属性为True,但实际上原DataFrame的更改会反映,_is_view属性是正确的。
记住所有情况下是视图还是副本在现实中不太可能,所以最终可能会逐一确认,但记住切片选择中是否省略可能会导致视图或副本的变化可能会有所帮助。
numpy.ndarray和pandas.DataFrame之间的内存共享
DataFrame和ndarray可以互相转换。DataFrame和ndarray之间也可能共享内存。
相关文章:pandas.DataFrame, Series与NumPy数组ndarray的相互转换
在这种情况下,可能可以相信np.shares_memory()的结果。
无论是DataFrame还是ndarray,都可以通过copy()方法生成副本。
从numpy.ndarray生成pandas.DataFrame
从ndarray生成DataFrame的情况。
a = np.array([[0, 1, 2], [3, 4, 5]])print(a)# [[0 1 2]# [3 4 5]]df = pd.DataFrame(a)print(df)# 0 1 2# 0 0 1 2# 1 3 4 5np.shares_memory()和DataFrame的_is_view属性返回True。print(np.shares_memory(a, df))# Trueprint(df._is_view)# True
修改ndarray的值时会反映到DataFrame,实际证实是视图。
a[0, 0] = 100print(a)# [[100 1 2]# [ 3 4 5]]print(df)# 0 1 2# 0 100 1 2# 1 3 4 5
并不总是视图,对于字符串情况是副本。
a_str = np.array([['a', 'b', 'c'], ['x', 'y', 'z']])
print(a_str)
# [['a' 'b' 'c']
# ['x' 'y' 'z']]df_str = pd.DataFrame(a_str)print(df_str)# 0 1 2# 0 a b c# 1 x y zprint(np.shares_memory(a_str, df_str))# Falseprint(df_str._is_view)# Falsea_str[0, 0] = 'A'
print(a_str)
# [['A' 'b' 'c']
# ['x' 'y' 'z']]print(df_str)# 0 1 2# 0 a b c# 1 x y z
从pandas.DataFrame生成numpy.ndarray
从DataFrame生成ndarray的情况。
DataFrame的各列数据类型dtype相同种类时是视图。
df_homo = pd.DataFrame([[0, 1, 2], [3, 4, 5]])print(df_homo)# 0 1 2# 0 0 1 2# 1 3 4 5print(df_homo.dtypes)# 0 int64# 1 int64# 2 int64# dtype: objecta_homo = df_homo.valuesprint(a_homo)# [[0 1 2]# [3 4 5]]print(np.shares_memory(a_homo, df_homo))# Truedf_homo.iat[0, 0] = 100print(df_homo)# 0 1 2# 0 100 1 2# 1 3 4 5print(a_homo)# [[100 1 2]# [ 3 4 5]]
异种情况是副本。
df_hetero = pd.DataFrame([[0, 'x'], [1, 'y']])
print(df_hetero)
# 0 1
# 0 0 x
# 1 1 yprint(df_hetero.dtypes)
# 0 int64
# 1 object
# dtype: objecta_hetero = df_hetero.values
print(a_hetero)
# [[0 'x']
# [1 'y']]print(np.shares_memory(a_hetero, df_hetero))
# Falsedf_hetero.iat[0, 0] = 100print(df_hetero)
# 0 1
# 0 100 x
# 1 1 yprint(a_hetero)
# [[0 'x']
# [1 'y']]