合并/连接具有不同元素的数组 [英] merging/concatenating arrays with different elements

查看:84
本文介绍了合并/连接具有不同元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在numpy中合并不同元素(matlab样式)的混合?

How to merge a mix of different elements (matlab style) in numpy?

[array([ 0.]), 0.0, 0.0011627, 0.0, 2.69, 0.0, array([ 3.8269, 7.0184]), array([ 4.4e-16, 2.1e+00])]

(我尝试过np.concatenate,但是显然它只将数组作为输入). 基本上,我想通过索引动态连接向量中的元素.我尝试过:

(I tried np.concatenate, but obviously it only takes arrays as input). Basically, I want to dynamically concatenate elements from a vector by indexing. I tried:

 V = np.array([1,2,3,4,5,6])
 Y = np.array([7,8,9,10,11,12])

 Z = np.array([V[0:2],Y[0],V[3],Y[1:3],V[4:],Y[4:]])

它可以工作,但是里面有数组元素.我只想要数字的平面向量(Matlab风格),后来我用一堆这些向量制作了一个矩阵(称为RES).甚至是一个简单的

It works, but has array elements inside. I just want a flat vector of numbers (Matlab style) as later I make a matrix (called RES) with a bunch of these vectors. Even a simple

 np.savetxt('TT',RES,fmt='%1.1e') 

失败,因为它期望浮点数而不是内部数组.

fails because it expects floats and not arrays inside.

猜猜这应该很简单. np.hstack完成任务.但是,还有其他简单的方法可以进行Matlab样式索引和制作吗?向量和标量的组合?

Guess this should be simple. np.hstack does the job. But is there any other easy way to do Matlab style indexing & combining of vectors and scalars?

推荐答案

您可以使用 np.r_ :

In [32]: Z = np.r_[V[0:2],Y[0],V[3],Y[1:3],V[4:],Y[4:]]

In [33]: Z
Out[33]: array([ 1,  2,  7,  4,  8,  9,  5,  6, 11, 12])

这篇关于合并/连接具有不同元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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