简体   繁体   中英

How to join slices of rows to create a new row in python

In Python, i need to split two rows in half, take the first half from row 1 and second half from row 2 and concatenate them into an array which is then saved as a row in another 2d array. for example

values=np.array([[1,2,3,4],[5,6,7,8]])

will become

Y[2,:]= ([1,2,7,8]))  // 2 is arbitrarily chosen 

I tried doing this with concatenate but got an error

only integer scalar arrays can be converted to a scalar index

x=values.shape[1] 
pop[y,:]=np.concatenate(values[temp0,0:int((x-1)/2)],values[temp1,int((x-1)/2):x+1])

temp0 and temp1 are integers, and values is a 2d integer array of dimensions (100,x)

np.concatenate takes a list of arrays, plus a scalar axis parameter (optional)

In [411]: values=np.array([[1,2,3,4],[5,6,7,8]])
     ...: 

Nothing wrong with how you split values :

In [412]: x=values.shape[1] 
In [413]: x
Out[413]: 4
In [415]: values[0,0:int((x-1)/2)],values[1,int((x-1)/2):x+1]
Out[415]: (array([1]), array([6, 7, 8]))

wrong:

In [416]: np.concatenate(values[0,0:int((x-1)/2)],values[1,int((x-1)/2):x+1])
----
TypeError: only integer scalar arrays can be converted to a scalar index

It's trying to interpret the 2nd argument as an axis parameter, hence the scalar error message.

right:

In [417]: np.concatenate([values[0,0:int((x-1)/2)],values[1,int((x-1)/2):x+1]])
Out[417]: array([1, 6, 7, 8])

There are other concatenate front ends. Here hstack would work the same. np.append takes 2 arrays, so would work - but too often people use it wrongly. np.r_ is another front end with different syntax.

The indexing might be clearer with:

In [423]: idx = (x-1)//2
In [424]: np.concatenate([values[0,:idx],values[1,idx:]])
Out[424]: array([1, 6, 7, 8])

Try numpy.append

numpy.append Documentation

np.append(values[temp0,0:int((x-1)/2)],values[temp1,int((x-1)/2):x+1])

You don't need splitting and/or concatenation. Just use indexing :

In [47]: values=np.array([[1,2,3,4],[5,6,7,8]])

In [48]: values[[[0], [1]],[[0, 1], [-2, -1]]]
Out[48]: 
array([[1, 2],
       [7, 8]])

Or ravel to get the flattened version:

In [49]: values[[[0], [1]],[[0, 1], [-2, -1]]].ravel()
Out[49]: array([1, 2, 7, 8])

As a more general approach you can also utilize np.r_ as following:

In [61]: x, y = values.shape

In [62]: values[np.arange(x)[:,None],[np.r_[0:y//2], np.r_[-y//2:0]]].ravel()
Out[62]: array([1, 2, 7, 8])

Reshape to split the second dimension in two; stack the part you want.

a = np.array([[1,2,3,4],[5,6,7,8]])
b = a.reshape(a.shape[0], a.shape[1]//2, 2)
new_row = np.hstack([b[0,0,:], b[1,1,:]])
#new_row = np.hstack([b[0,0], b[1,1]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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