首页 > 解决方案 > Create a Numpy array from parts of other arrays in Python

问题描述

EDIT

So I just understand now that Python and Numpy just don't do polymorphism very well. Given the same data, it has to be put into the right form before most functions can use it. So expecting Python to be able to 'one-line' something is beyond its capabilities.

Just for comparison, MATLAB doesn't do polymorphism very well either but it's much less noticeable as by default it keeps all numeric data as a 2D array so the majority of functions will work with the majority of data - making it soooo much easier

EDIT

I'm pretty new to Python and struggling to create new arrays out of existing arrays:

In MATLAB the following works to create a column vector from other column vectors:

a = [b(5:6); c(N:M); d(1:P); e(Q)]

with a lot of computational flexibility (Q could be a vector for example).

In Python, I can't find a nice command to add multiple 1D NumPy arrays together and it seems to have lots of issues with single values as it changes them from NumPy arrays to some other format, WHY?!

Can anyone give me a single line of code to carry out the above? It'd be great to see - so far all I've got is lines and lines of checking for the indexing variables (N, M, P, Q) and soooo many np.array(..)'s everywhere to try and keep things the same data type.

I've tried np.append but that doesn't work for multiple vectors (I could nest them but that seems very ugly, esp if I need to add many arrays) and np.concatenate complains that something is 0-dimensional, I don't understand that at all.

标签: pythonarraysnumpy

解决方案


concatenate一堆一维数组没有问题:

In [52]: np.concatenate([np.array([1,2,3]), np.ones((2,)), np.array([1])])
Out[52]: array([1., 2., 3., 1., 1., 1.])

如果一个参数是标量:

In [53]: np.concatenate([np.array([1,2,3]), np.ones((2,)), 1])
Traceback (most recent call last):
  File "<ipython-input-53-51b00c09f677>", line 1, in <module>
    np.concatenate([np.array([1,2,3]), np.ones((2,)), 1])
  File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 2 has 0 dimension(s)

它从最后一个数组

In [57]: np.array(1)
Out[57]: array(1)

但这是一个 0d 数组。在 MATLAB 中,这将是 2d - 一切都是 2d,没有真正的标量。请记住,numpy在 python 中工作,它具有标量和列表。MATLAB 一直是矩阵...

numpy 数组也可以是 0d 或 1d。没有人为的 2d 下限。它是一种通用数组语言,而不仅仅是矩阵。在 MATLAB 中,甚至 3d 也是对原始 2d 的调整。

hstack添加一个调整以确保所有参数至少为 1d:

In [54]: np.hstack([np.array([1,2,3]), np.ones((2,)), 1])
Out[54]: array([1., 2., 3., 1., 1., 1.])

即使在 MATLAB/Octave 中,尺寸不匹配也会出现问题:

>> a = [3:5; [1,2,3]]
a =    
   3   4   5
   1   2   3

>> a = [3:5; [1,2,3]; 4]
error: vertical dimensions mismatch (2x3 vs 1x1)

>> a = [3:5; [1,2,3,4]]
error: vertical dimensions mismatch (1x3 vs 1x4)
>> a = [3:5, [1,2,3,4]]
a =    
   3   4   5   1   2   3   4

>> a = [3:5, [1,2,3,4],5]
a =
   3   4   5   1   2   3   4   5

推荐阅读