python - Numpy:使用 numpy.ndarray.view 的永久更改?

标签 python numpy

如果我想永久更改 numpy 数组的数据类型,重新分配是最好的方法吗?

下面是一个语法示例:

import numpy as np
x = np.array([1],dtype='float')
x = x.view(dtype=('x','float"))

但是,我更愿意“就地”更改数据类型。

有没有办法就地改变数组的数据类型?还是做类似这样的东西更好?:

x = x.view(dtype=('x',"float")).copy()

最佳答案

真的没有“永久”数据类型。

Numpy 数组基本上只是一种查看内存缓冲区的方式。

从 numpy 的角度来看, View 只是在不制作副本的情况下对同一内存缓冲区进行切片和切 block 的不同方式。

不过请记住,这让您可以对内存缓冲区的解释方式进行低级控制。

例如:

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

print 'An integer array:', x
print 'But if we view it as a float:', x.view(np.float)
print "...It's probably not what we expected..."

这会产生:

An integer array: [0 1 2 3 4 5 6 7 8 9]
But if we view it as a float: [  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]
...It's probably not what we expected...

因此,在这种情况下,我们将原始内存缓冲区的底层位解释为 float 。

如果我们想制作一个新副本,将整数重铸为 float ,我们将使用 x.astype(np.float)

View (dtypes...切片也返回一个 View ,虽然那是一个单独的主题。)之所以如此有用,是因为您可以做一些非常好的技巧,而不必在内存中复制东西。

例如,如果您想将 float 就地转换为整数(不复制内存),您可以在 View 中使用一些技巧来完成此操作。 (基于@unutbu 的回答 on this question 。)

import numpy as np
x = np.arange(10, dtype=np.int)
print 'The original int array:', x

# We would have just used y = x.astype(np.float), but it makes a copy.
# This doesn't. If we're worried about memory consumption, it's handy!
y = x.view(np.float)
y[:] = x

print 'The new float array:', y
print 'But, the old int array has been modified in-place'
print x
print "They're both views into the same memory buffer!"

同样,您可以进行各种低级位操作:

import numpy as np
x = np.arange(10, dtype=np.uint16)
y = x.view(np.uint8)

print 'The original array:', x
print '...Viewed as uint8:', y
print '...Which we can do some tricks with', y[::2]

# Now let's interpret the uint16's as two streams of uint8's...
a, b = y[::2], y[1::2]
b[:] = np.arange(10, dtype=np.uint8)
print a
print b
print x
print y
# Notice that the original is modified... We're not duplicating memory anywhere!

要回答您的问题,“更好”是相对的。您想要一份副本,还是想要以不同的方式查看相同的内存缓冲区?

作为旁注,astype 总是制作副本,无论“输入”和“输出”数据类型如何。这通常是人们在引用 view 时真正想要的。 (例如,如果您想在整数和 float 之间进行转换,请使用 astype,而不是 View ,除非您需要对内存使用进行微观管理。)

关于python - Numpy:使用 numpy.ndarray.view 的永久更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7824188/

相关文章:

Python编译eval?

Javascript - 如何在使用 Google App Engine 时加载 javascript 库?

python - 使用 numpy 离散逼近高斯分布

python - Pandas 中数据框行中的数据框列

python - 使用 Python 请求测量网站加载时间

python - 在 django 中通过 SSO + OpenID 对 Google Apps 自定义域的用户进行身份验证

python - Numpy 矩阵乘法,而不是乘以 XOR 的元素

python - 线性回归——降低自由度

python - 如何将逆向转置应用到 numpy 数组

python - 在python中解析一行的文本文件