在Python 3中,将np.array对象类型转换为float类型,并带有可变数量的object元素 [英] In Python 3, convert np.array object type to float type, with variable number of object element
问题描述
我有一个以dtype为对象的np.array.这里的每个元素都是一个np.array,其dtype为float,形状为(2,2)---在数学上,它是一个2×2矩阵.我的目标是通过将所有对象类型元素转换为浮点类型元素来获得一个二维矩阵.下面的示例可以更好地说明这一点.
I have a np.array with dtype as object. Each element here is a np.array with dtype as float and shape as (2,2) --- in maths, it is a 2-by-2 matrix. My aim is to obtain one 2-dimenional matrix by converting all the object-type element into float-type element. This can be better presented by the following example.
dA = 2 # dA is the dimension of the following A, here use 2 as example only
A = np.empty((dA,dA), dtype=object) # A is a np.array with dtype as object
A[0,0] = np.array([[1,1],[1,1]]) # each element in A is a 2-by-2 matrix
A[0,1] = A[0,0]*2
A[1,0] = A[0,0]*3
A[1,1] = A[0,0]*4
我的目标是拥有一个矩阵B(B的尺寸为2 * dA乘2 * dA).数学中B的形式应为
My aim is to have one matrix B (the dimension of B is 2*dA-by-2*dA). The form of B in maths should be
B =
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4
如果dA固定为2,那么事情会更容易,因为我可以硬编码
If dA is fixed at 2, then things can be easier, because I can hard-code
a00 = A[0,0]
a01 = A[0,1]
a10 = A[1,0]
a11 = A[1,1]
B0 = np.hstack((a00,a01))
B1 = np.hstack((a10,a11))
B = np.vstack((B0,B1))
但是实际上,dA是一个变量,它可以是2或任何其他整数.那我不知道该怎么做.我认为嵌套循环可以有所帮助,但也许您有一些绝妙的主意.如果在MATLAB中有像cell2mat这样的函数,那就太好了.因为在这里您可以在MATLAB中将A [i,j]视为一个单元格.
But in reality, dA is a variable, it can be 2 or any other integer. Then I don't know how to do it. I think nested for loops can help but maybe you have brilliant ideas. It would be great if there is something like cell2mat function in MATLAB. Because here you can see A[i,j] as a cell in MATLAB.
谢谢.
推荐答案
这是一种快速方法.
您的A
:
In [137]: A
Out[137]:
array([[array([[1, 1],
[1, 1]]), array([[2, 2],
[2, 2]])],
[array([[3, 3],
[3, 3]]), array([[4, 4],
[4, 4]])]], dtype=object)
使用 numpy.bmat
,但将A
首先显示为python列表,因此bmat
会执行我们想要的操作:
Use numpy.bmat
, but convert A
to a python list first, so bmat
does what we want:
In [138]: B = np.bmat(A.tolist())
In [139]: B
Out[139]:
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
结果实际上是numpy.matrix
.如果需要常规的numpy数组,请使用matrix
对象的.A
属性:
The result is actually a numpy.matrix
. If you need a regular numpy array, use the .A
attribute of the matrix
object:
In [140]: B = np.bmat(A.tolist()).A
In [141]: B
Out[141]:
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
这是另一种选择. (它仍然使用A.tolist()
.)
In [164]: np.swapaxes(A.tolist(), 1, 2).reshape(4, 4)
Out[164]:
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
在一般情况下,您将需要以下内容:
In the general case, you would need something like:
In [165]: np.swapaxes(A.tolist(), 1, 2).reshape(A.shape[0]*dA, A.shape[1]*dA)
Out[165]:
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
这篇关于在Python 3中,将np.array对象类型转换为float类型,并带有可变数量的object元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!