简体   繁体   English

如何在 numpy 中将 1D arrays 视为(1 by n)2D arrays?

[英]How to treat 1D arrays as (1 by n) 2D arrays in numpy?

I apologize if this has been asked before, but I can't seem to find an answer or I am not searching for the answer correctly.如果之前有人问过这个问题,我深表歉意,但我似乎找不到答案,或者我没有正确寻找答案。

I am currently writing code in python using numpy and my function takes a input as a matrix.我目前正在使用 numpy 在 python 中编写代码,而我的 function 将输入作为矩阵。 I want to view a 1D array as a (1 by n) 2D array.我想将一维数组视为(1×n)二维数组。

Here is a minimal example of my issue.这是我的问题的一个最小示例。 The following function takes input two matrices and adds the upper left element of the first matrix and adds it to the bottom right element of the second matrix.下面的 function 取输入两个矩阵,将第一个矩阵的左上角元素加到第二个矩阵的右下角元素上。

import numpy as np


def add_corners(A, B):
    r = A[0, 0] + B[B.shape[0] - 1, B.shape[1] - 1]
    return r


C = np.array([[1, 2, 3], [4, 5, 6]])
D = np.array([[9, 8], [7, 6], [5, 4], [10, 11]])
E = np.array([1, 2, 3, 4, 5])

print(add_corners(C, D))
print(add_corners(C, E))

print(add_corners(C,E)) leads to an error, since E.shape[1] is not well defined. print(add_corners(C,E))导致错误,因为E.shape[1]定义不明确。 Is there a way to get around this without having to add an if statement to check if my input contains a 1D array?有没有办法解决这个问题而不必添加 if 语句来检查我的输入是否包含一维数组? That is, I want to refer to the entries of E as E[1,x] as opposed to just E[x] .也就是说,我想将 E 的条目称为E[1,x]而不是E[x]

Any help is greatly appreciated!任何帮助是极大的赞赏!

What you need is to add an additional dimension.您需要添加一个额外的维度。 You could either do:你可以这样做:

add_corners(C, E[:, None])

or with np.expand_dims :或使用np.expand_dims

add_corners(C, np.expand_dims(E, -1))

Here's how it looks like:这是它的样子:

>>> E
array([1, 2, 3, 4, 5])

>>> E[:, None]
array([[1],
       [2],
       [3],
       [4],
       [5]])

>>> E[:, None].shape
(5, 1)

For a much easier and convenient way you can use the flat iterator:为了更容易和方便的方式,您可以使用平面迭代器:

def add_corners(A, B):
    return A.flat[0] + B.flat[-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM