您的位置:首页 > 编程语言 > Python开发

『Numpy』numpy.ndarray.view_数组视图_reshape、数组切片、数组内存开辟分析

2018-04-04 10:23 639 查看
在计算机中,没有任何数据类型是固定的,完全取决于如何看待这片数据的内存区域。
在numpy.ndarray.view中,提供对内存区域不同的切割方式,来完成数据类型的转换,而无须要对数据进行额外的copy,可以节约内存空间,我们可以将view看做对内存的展示方式。
np.ascontiguousarray()

1、使用示例

import numpy as np
x = np.arange(10, dtype=np.int)

print('An integer array:', x)
print ('An float array:', x.view(np.float))



[/code]
An integer array: [0 1 2 3 4 5 6 7 8 9]

An float array:
[ 0.00000000e+000 4.94065646e-324
9.88131292e-324 1.48219694e-323 1.97626258e-323
2.47032823e-323 2.96439388e-323 3.45845952e-323
3.95252517e-323 4.44659081e-323]
[/code]

在实际使用中我们往往会采取更复杂的dtype(也就是说view可以与dtype搭配使用)输出内存中的值,在『Numpy』数组和内存_下篇_numpy结构化数组中,我们示范了对于结构化数组的较为复杂的view使用。

2、view和copy

numpy.reshape()这个函数:

对于其返回值的解释:
Returns
-------
reshaped_array : ndarray
This will be a new view object if possible; otherwise, it will
be a copy. Note there is no guarantee of the *memory layout* (C- or
Fortran- contiguous) of the returned array.

其返回值可能是一个view,或是一个copy。相应的条件为:
  1、返回一个view条件:数据区域连续的时候
  2、反之,则返回一个copy

我们看一看连续数组和非连续数组

a = np.zeros([2,10], dtype=np.int32)
b = a.T  # 转置破坏连续结构

a.flags['C_CONTIGUOUS']  # True
b.flags['C_CONTIGUOUS']  # False

np.may_share_memory(a,b)  # True
b.base is a  # True
id(b)==id(a)  # False

a.shape = 20  # a的shape变了
a.flags['C_CONTIGUOUS']  # True

# b.shape = 20
# AttributeError: incompatible shape for a non-contiguous array
# 想要使用指定shape的方式,只能是连续数组,但是reshape方法由于不改变原数组,所以reshape不受影响


3、数组切片是否会copy数据?

不过,数组的切片对象虽然并非contiguous,但是对它的reshape操作并不会copy新的对象,

a = np.arange(16).reshape(4,4)

print(a.T.flags['C_CONTIGUOUS'],a[:,0].flags['C_CONTIGUOUS'])
# False False

print (np.may_share_memory(a,a.T.reshape(16)),
np.may_share_memory(a,a[:,0].reshape(4)))
# False True


如果进一步尝试对reshape后的对象赋值,会改变原本的a数组

a = np.arange(16).reshape(4,4)
b = a[:,0].reshape(2,2)

‘’‘
a
array([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])
b
array([[ 0,  4],
[ 8, 12]])
’‘’

b += 1

‘’‘
b
array([[ 1,  5],
[ 9, 13]])
a
array([[ 1,  1,  2,  3],
[ 5,  5,  6,  7],
[ 9,  9, 10, 11],
[13, 13, 14, 15]])
’‘’
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐