dtype Int64 没有 return 底层数据视图?

dtype Int64 doesn't return view of underlying data?

我有两个大小为 (5, 5) 的数据帧,一个是 dtype int64,另一个是 pd.Int64Dtype.

np.random.seed(2021)
data = np.arange(25).reshape((5, 5))
one  = pd.DataFrame(data, dtype='int64')
two  = pd.DataFrame(data.copy(), dtype='Int64') # Notice the capital 'I'
r, c = np.random.randint(0, 5, (2, 5))

当我尝试更改基础数据时出现问题。

one.to_numpy()[r, c] = 99 # Changes the underlying data
print(one)
    0   1   2   3   4
0   0  99   2   3   4
1   5   6   7   8  99
2  10  11  12  13  14
3  15  99  17  18  19
4  99  99  22  23  24

two.to_numpy()[r, c] = 99 # Doesn't change the underlying data
print(two)
    0   1   2   3   4
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
4  20  21  22  23  24

我明白 DataFrame.to_numpy 不一定 return 一个视图。

DataFrame.to_numpy():

copy: bool, default False

Whether to ensure that the returned value is not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary.

如何以矢量化方式更改 DataFrame 中的给定位置(rc)?我有一个使用 for loop + .iloc 的解决方案。对于它的价值,我的 pandas' 版本是 1.3.1.

具有 dtype Int64 的扩展块不支持 numpy 分配是正确的,因为它们被视为 5 个独立的块而不是单个数字块。这会影响生成对底层结构的统一可修改引用的能力。

您可以通过从管理器访问块来观察这一点(注意这只是为了观察目的):

print('One Blocks')
for blk in one._mgr.blocks:
    print(blk)

print('Two Blocks')
for blk in two._mgr.blocks:
    print(blk)

输出:

One Blocks
NumericBlock: slice(0, 5, 1), 5 x 5, dtype: int64
Two Blocks
ExtensionBlock: slice(0, 1, 1), 1 x 5, dtype: Int64
ExtensionBlock: slice(1, 2, 1), 1 x 5, dtype: Int64
ExtensionBlock: slice(2, 3, 1), 1 x 5, dtype: Int64
ExtensionBlock: slice(3, 4, 1), 1 x 5, dtype: Int64
ExtensionBlock: slice(4, 5, 1), 1 x 5, dtype: Int64

请注意,DataFrame (two) 将这些作为单独的底层结构,这意味着转换为数组调用 _interleave,正如评论中所说的“底层数据已在 _interleave 中复制”。

注意对于包含多个块的所有数据帧都是如此。

意思很简单:

df = pd.DataFrame({'A': [1, 2], 'B': ['a', 'b']})
df.to_numpy()[0, 0] = 5  # No Change
print(df)

   A  B
0  1  a
1  2  b

也不能这样修改

*参考区块

# df._mgr.blocks

NumericBlock: slice(0, 1, 1), 1 x 2, dtype: int64
ObjectBlock: slice(1, 2, 1), 1 x 2, dtype: object

考虑到这一点,我们必须使用 to_numpy 生成的副本并重建 DataFrame:

a = two.to_numpy()  # Store New Array
a[r, c] = 99  # Update The Values
# Reconstruct the DataFrame
two = pd.DataFrame(a, index=two.index, columns=two.columns, dtype='Int64')

astype 也可以与已知的数据类型一起使用,以确保列映射到适当的数据类型(这可能对多个数据类型的实例有帮助):

two = pd.DataFrame(a, index=two.index, columns=two.columns).astype(two.dtypes)

输出:

print(two)

    0   1   2   3   4
0   0  99   2   3   4
1   5   6   7   8  99
2  10  11  12  13  14
3  15  99  17  18  19
4  99  99  22  23  24


print(two.dtypes)
0    Int64
1    Int64
2    Int64
3    Int64
4    Int64
dtype: object

然而,考虑到这种单一的替换,使用 numpy 构建 2D 蒙版可能是更好的方法:

# Build Boolean Mask (default False)
result = np.zeros(two.shape, dtype='bool')
result[r, c] = True  # Set True Locations
two = two.mask(result, 99)  # DataFrame.mask to replace values

DataFrame.where的逆掩码:

# Build Boolean Mask (default True)
result = np.ones(two.shape, dtype='bool')
result[r, c] = False  # Set False Locations
two = two.where(result, 99)  # DataFrame.where to replace values

两者都产生:

print(two)
    0   1   2   3   4
0   0  99   2   3   4
1   5   6   7   8  99
2  10  11  12  13  14
3  15  99  17  18  19
4  99  99  22  23  24


print(two.dtypes)
0    Int64
1    Int64
2    Int64
3    Int64
4    Int64
dtype: object

*这些方法的好处是不会丢失 dtype 信息。