Numpy:如何在列中堆叠数组? [英] Numpy: How to stack arrays in columns?

查看:70
本文介绍了Numpy:如何在列中堆叠数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 n 个相同长度的 numpy 数组.我现在想创建一个 numpy 矩阵,这样矩阵的每一列都是 numpy 数组之一.我怎样才能做到这一点?现在我在循环中执行此操作,但会产生错误的结果.

Let's say that I have n numpy arrays of the same length. I would like to now create a numpy matrix, sucht that each column of the matrix is one of the numpy arrays. How can I achieve this? Now I'm doing this in a loop and it produces the wrong results.

注意:我必须能够将它们一个接一个地迭代地堆叠在一起.

Note: I have to be able to stack them next to each other one by one iteratively.

我的代码看起来假设 get_array 是一个函数,它根据其参数返回某个数组.直到循环之后,我才知道我将拥有多少列.

my code looks like assume that get_array is a function that returns a certain array based on its argument. I don't know until after the loop, how many columns that I'm going to have.

matrix = np.empty((n_rows,))
for item in sorted_arrays:
    array = get_array(item)
    matrix = np.vstack((matrix,array))

任何帮助将不胜感激

推荐答案

一次又一次,我们建议将数组收集在一个列表中,并通过一次调用生成最终的数组.这样效率更高,而且通常更容易做对.

Time and again, we recommend collecting the arrays in a list, and making the final array with one call. That's more efficient, and usually easier to get right.

alist = []
for item in sorted_arrays:
    alist.append(get_array(item)

alist = [get_array(item) for item in sorted_arrays]

有多种组合列表的方法.由于您需要列,并假设 get_array 生成大小相等的一维数组:

There are various ways of assembling the list. Since you want columns, and assuming get_array produces equal sized 1d arrays:

arr = np.column_stack(alist)

按行收集它们并转置也可以:

Collecting them in rows and transposing that works too:

arr = np.array(alist).T
arr = np.vstack(alist).T
arr = np.stack(alist).T
arr = np.stack(alist, axis=1)

如果数组已经是二维的

arr = np.concatenate(alist, axis=1)

所有 stack 变体都使用 concatenate,只是在调整输入数组形状的方式上有所不同.使用concatenate的关键是了解尺寸和形状,以及如何根据需要添加尺寸.迟早,他们应该会熟练掌握这种编码.

All the stack variations use concatenate, just varying in how they tweak the shape(s) of the input arrays. The key to using concatenate is to understand the dimensions and shapes, and how to add dimensions as needed. That should, soon or later, become fluent in that kind of coding.

如果它们的形状或尺寸不同,事情就会变得更糟.

If they vary in shape or dimensions, things get messier.

将数组放在预先分配的数组中同样好.但是你需要知道想要的最终形状

Equally good is to put the arrays in a pre-allocated array. But you need to know the desired final shape

arr = np.zeros((m,n), dtype)
for i, item in enumerate(sorted_arrays):
    arr[:,i] = get_array(item)

nlen(sorted_arrays)mget_array(item) 之一的长度.您还需要知道预期的 dtype(int、float 等).

n is len(sorted_arrays), and m is the length of one of get_array(item). You also need to know the expected dtype (int, float etc).

这篇关于Numpy:如何在列中堆叠数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆