NumPy 中的拼接数组?
我想在 NumPy 中执行某种拼接。假设我有两个数组,a
和b
:
>>> a
array([[ 1, 10],
[ 2, 20],
[ 5, 30]])
>>> b
array([[ 1, 11],
[ 3, 31],
[ 4, 41]])
我想将它们拼接在一起形成以下数组,c
:
>>> c
array([[ 1., 10.],
[ 2., 20.],
[ 3., nan],
[ 4., nan],
[ 5., 30.]])
也就是说,我拼接将 b
第一列的值转换为 a
,而不关心第二列。
我当然可以很容易地自己实现这个,但如果让 NumPy 为我做的话会更好。这可能吗?
I'd like to perform a splice of sorts in NumPy. Let's say I have two arrays, a
and b
:
>>> a
array([[ 1, 10],
[ 2, 20],
[ 5, 30]])
>>> b
array([[ 1, 11],
[ 3, 31],
[ 4, 41]])
which I want to splice together into the following array, c
:
>>> c
array([[ 1., 10.],
[ 2., 20.],
[ 3., nan],
[ 4., nan],
[ 5., 30.]])
That is, I splice the values from the first column of b
into a
without bothering about the second column.
I could of course implement this myself pretty easily, but it would be nicer to have NumPy do it for me instead. Is that possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将两者堆叠在一起然后排序。然而,这并没有考虑到索引 1 出现两次的事实。不确定这是一个很大的改进......
You could stack the two together and then sort. However, this doesn't take care of the fact that you have two occurrences of the index 1. Not sure this is a great improvement...
我认为 NumPy 中没有任何东西可以做到这一点。您是否需要确切的结果(按顺序,第二列具有未定义的值)?也许有一些接近的东西对最终目标仍然有用。
I don't think there is anything in NumPy to do that. Do you need exactly that result (in order, second column with undefined value)? Maybe there is something close that would still be useful for the end goal.
mishaF 的答案只缺少最后一步——使最后一列的条目唯一。获取
c
的完整代码(除了 dtype,它在帖子中从int
更改为float
)是The answer by mishaF is only missing the last step -- making the entries of the last column unique. The full code to get your
c
(except for the dtype, which changes fromint
tofloat
in your post) is