在numpy中将一维数组转换为二维数组 [英] Convert a 1D array to a 2D array in numpy

查看:414
本文介绍了在numpy中将一维数组转换为二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过指定二维数组中的列数将一维数组转换为二维数组.像这样工作的东西:

I want to convert a 1-dimensional array into a 2-dimensional array by specifying the number of columns in the 2D array. Something that would work like this:

> import numpy as np
> A = np.array([1,2,3,4,5,6])
> B = vec2matrix(A,ncol=2)
> B
array([[1, 2],
       [3, 4],
       [5, 6]])

numpy 是否有一个函数可以像我编写的函数vec2matrix"一样工作?(我知道您可以像二维数组一样索引一维数组,但这不是我拥有的代码中的一个选项 - 我需要进行此转换.)

Does numpy have a function that works like my made-up function "vec2matrix"? (I understand that you can index a 1D array like a 2D array, but that isn't an option in the code I have - I need to make this conversion.)

推荐答案

您想要 重塑数组.

You want to reshape the array.

B = np.reshape(A, (-1, 2))

其中 -1 从输入数组的大小推断新维度的大小.

where -1 infers the size of the new dimension from the size of the input array.

这篇关于在numpy中将一维数组转换为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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