cbind (R function) equivalent in numpy
Asked Answered
F

2

9

Here's the behavior I want:

import numpy as np
x = np.array([[1,2],[3,4]])
y = np.array([5, 6])
cbind(x,y) # desired result: np.array([[1,2,5],[3,4,6]])

Seems like it should be easy, but the options I found on http://mathesaurus.sourceforge.net/r-numpy.html (concatenate, hstack, etc.) don't work, e.g.:

np.hstack((x,y))

gives

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "X/site-packages/numpy/core/shape_base.py", line 288, in hstack
    return _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions
Fanchon answered 14/5, 2017 at 7:49 Comment(2)
that's not what cbind doesGupton
It's not? What does cbind do?Fanchon
F
15

More googling found the following answer https://mcmap.net/q/80370/-how-do-i-add-an-extra-column-to-a-numpy-array:

np.c_[x,y]

gives

array([[1, 2, 5],
   [3, 4, 6]])

I'll leave it to the StackOverflow stylistas to decide whether I should delete this entire question as a duplicate.

Fanchon answered 14/5, 2017 at 7:53 Comment(0)
A
3

Using Column Stack will do the trick:

https://numpy.org/doc/stable/reference/generated/numpy.column_stack.html

Example: this will cbind the two 4 X 1 vector together

a = np.random.randn(4,1)
b = np.random.randn(4,1)
np.column_stack((a,b))
Alwyn answered 17/5, 2021 at 5:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.