NumPy 中的拼接数组?

发布于 2024-10-08 10:22:51 字数 593 浏览 2 评论 0原文

我想在 NumPy 中执行某种拼接。假设我有两个数组,ab

>>> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我纯我任性 2024-10-15 10:22:52

您可以将两者堆叠在一起然后排序。然而,这并没有考虑到索引 1 出现两次的事实。不确定这是一个很大的改进......

 b[:,1]=np.nan
 c = np.vstack((a,b))
 c.sort(0)

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...

 b[:,1]=np.nan
 c = np.vstack((a,b))
 c.sort(0)
一江春梦 2024-10-15 10:22:52

我认为 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.

凉世弥音 2024-10-15 10:22:51

mishaF 的答案只缺少最后一步——使最后一列的条目唯一。获取 c 的完整代码(除了 dtype,它在帖子中从 int 更改为 float)是

b[:,1]=numpy.nan
c = numpy.r_[a, b]
c.sort(0)
c = c[numpy.unique(c[:,0], True)[1]]

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 from int to float in your post) is

b[:,1]=numpy.nan
c = numpy.r_[a, b]
c.sort(0)
c = c[numpy.unique(c[:,0], True)[1]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文