nby

时间:2017-05-14 07:49:27

标签: python r numpy cbind

这是我想要的行为:

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]])

似乎应该很容易,但我在http://mathesaurus.sourceforge.net/r-numpy.html(连接,hstack等)上找到的选项不起作用,例如:

np.hstack((x,y))

给出

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

2 个答案:

答案 0 :(得分:3)

更多Google搜索找到了以下答案https://stackoverflow.com/a/8505658/1890660

np.c_[x,y]

给出

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

我将把它留给StackOverflow造型师来决定是否应该将整个问题删除为副本。

答案 1 :(得分:0)

使用列堆栈可以解决问题:

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

示例:这会将两个 4 X 1 向量绑定在一起

a = np.random.randn(4,1)
b = np.random.randn(4,1)
np.column_stack((a,b))