Home > Back-end >  How to append column values to numpy array?
How to append column values to numpy array?

Time:01-24

I have a numpy array arr:

array([[1., 2., 3.],
       [4., 2., 1.],
       [1., 2., 0.]])

Also I have pandas dataframe df:

col1   col2
a       2
b       7
c       10

I want to append values from col2 to array to get this result:

array([[1., 2., 3., 2.],
       [4., 2., 1., 7.],
       [1., 2., 0., 10.]])

this didn't work arr[:, :-1] = df["col2"]

How to do that?

CodePudding user response:

hstack works, another way is this:

from numpy import array, c_
from pandas import DataFrame

arr = array([
    [1., 2., 3.],
    [4., 2., 1.],
    [1., 2., 0.]
])

df = DataFrame([
    ['a', 2], 
    ['b', 7], 
    ['c', 10]
], columns=['col1', 'col2'])

arr = c_[arr, df['col2']]
print(arr)

Result:

[[ 1.  2.  3.  2.]
 [ 4.  2.  1.  7.]
 [ 1.  2.  0. 10.]]

I like the brevity and simplicity of c_[arr, df['col2']], but of course it's not exactly descriptive, so only people that are aware of it will get its meaning https://numpy.org/doc/stable/reference/generated/numpy.c_.html

CodePudding user response:

Use np.hstack:

np.hstack([arr, df.col2.to_frame()])

You need to make sure both of them have the same shape, that's why the to_frame part. You could also just add another axis directly df.col2[:, None].

  •  Tags:  
  • Related