I have a 2D numpy array and I need to add one column before the first column as id.
My array is this:
x = [['8' '4' 'M' '55' '7' 'S' '7' '2']
 ['36' '4' 'F' '58' '1' 'M' '7' '7']
 ['33' '3' 'M' '34' '4' 'M' '2' '3']
 ['43' '1' 'F' '64' '4' 'M' '7' '68']
 ['1' '2' 'M' '87' '4' 'M' '7' '1']]
The column that I want to add is this y = ['1' '2' '3' '4' '5']
And the target output is:
z = [['1' '8' '4' 'M' '55' '7' 'S' '7' '2']
 ['2' '36' '4' 'F' '58' '1' 'M' '7' '7']
 ['3' '33' '3' 'M' '34' '4' 'M' '2' '3']
 ['4' '43' '1' 'F' '64' '4' 'M' '7' '68']
 ['5' '1' '2' 'M' '87' '4' 'M' '7' '1']]
Is there any way that I can do it? (I can find a solution for inserting a row, but not a column)
define your new column:
col = np.array(['1','2','3','4','5'])
col.shape = (5,1)
and insert it at the start:
target = np.hstack((col, x))
for inserting at any given position i, you can do it like this:
target = np.hstack((x[:,:i], col, x[:,i:]))
But it looks to me like using a pandas dataframe rather than a numpy array would be a better option...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With