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 line 1, take the second half from line 2 and concatenate them into an array, and then save the array as a row in another two-dimensional 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 to do this using a connection but got an error
Only integer scalar arrays can be converted to scalar indexes
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 are two-dimensional integer arrays with dimensions (100,x).
Solution
np.concatenate
takes a list of arrays, plus scalar axis
parameters (optional).
In [411]: values=np.array([[1,2,3,4],[5,6,7,8]])
...:
There is no problem with the way the values
are split:
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]))
Error:
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 tries to interpret the second parameter as an axis parameter, so it gets a 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 frontends
. Here hstack
does the same thing. np.append
takes 2 arrays, so it works – but people often use it incorrectly. np.r_
is another frontend with a different syntax.
The index could be clearer:
In [423]: idx = (x-1)//2
In [424]: np.concatenate([values[0,:idx],values[1,idx:]])
Out[424]: array([1, 6, 7, 8])