Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - merging/concatenating arrays with different elements

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])]

(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:]])

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use 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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...