python,如何在数组中提取相同元素的列索引,并将它们存储在新数组中,内部具有相同的数字

发布于 2025-01-26 08:12:14 字数 411 浏览 5 评论 0原文

假设我有一个1D数组,我想在此数组中获取相同数字的所有列索引,然后将它们存储在单独的数组中。

,所有3的所有数字均在索引0,3,12中,对于索引4,5等。

x = np.array([3,6,8,3,1,1,5,8,5,0,2,0,3])

例如

a = np.array([0,3,12]) # Number 3
b = np.array([1]) # Number 6
c = np.array([2,7]) # Number 8
d = np.array([4,5]) # Number 1
e = np.array([9,11]) # Number 0
f = np.array([6,8]) # Number 5
g = np.array([10]) # Number 2

Let's say I have a 1D array and I want to obtain all the column indexes of the same numbers in this array and store them in separate arrays.

For example, all the numbers for 3 are in index 0,3,12, for 1 in index 4,5 etc.

x = np.array([3,6,8,3,1,1,5,8,5,0,2,0,3])

So the output would be

a = np.array([0,3,12]) # Number 3
b = np.array([1]) # Number 6
c = np.array([2,7]) # Number 8
d = np.array([4,5]) # Number 1
e = np.array([9,11]) # Number 0
f = np.array([6,8]) # Number 5
g = np.array([10]) # Number 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

哑剧 2025-02-02 08:12:14
np.argwhere(x==3)

输出:

array([[ 0],
       [ 3],
       [12]])

编辑:
如果您想要一个1D数组,只需在输出上使用Flatten()方法,

大多数功能都可以在Numpy中搜索Numpy中的索引,该索引从下一次;););)

np.argwhere(x==3)

Outputs:

array([[ 0],
       [ 3],
       [12]])

Edit:
if you want an 1D Array just use the flatten() method on the output

Most functions to search for indexes in numpy starts with arg for the next time ;)

旧人哭 2025-02-02 08:12:14
def same_num_index(arr):
    output = {k:[] for k in set(arr)}
    for i,x in enumerate(arr):
        output[x].append(i)
    return output

x = np.array([3,6,8,3,1,1,5,8,5,0,2,0,3])

index_of = same_num_index(x)

index_of[3] 

生产:

[0,3,12]

编辑:

@jack的答案使用numpy内置功能,应是首选

def same_num_index(arr):
    output = {k:[] for k in set(arr)}
    for i,x in enumerate(arr):
        output[x].append(i)
    return output

x = np.array([3,6,8,3,1,1,5,8,5,0,2,0,3])

index_of = same_num_index(x)

index_of[3] 

produces:

[0, 3, 12]

Edit:

@jack's answer uses numpy built-in function and should be preferred

南风起 2025-02-02 08:12:14

您可以将numpy.uniquereturn_inversereturn_counts flags这样

import numpy as np

x = np.array([3,6,8,3,1,1,5,8,5,0,2,0,3])

unq,inv,cnt=np.unique(x,0,1,1)

dict(zip(unq,np.split(inv.argsort(),cnt[:-1].cumsum())))
# {0: array([ 9, 11]), 1: array([4, 5]), 2: array([10]), 3: array([ 0,  3, 12]), 5: array([6, 8]), 6: array([1]), 8: array([2, 7])}

You can use numpy.unique with the return_inverse and return_counts flags like so:

import numpy as np

x = np.array([3,6,8,3,1,1,5,8,5,0,2,0,3])

unq,inv,cnt=np.unique(x,0,1,1)

dict(zip(unq,np.split(inv.argsort(),cnt[:-1].cumsum())))
# {0: array([ 9, 11]), 1: array([4, 5]), 2: array([10]), 3: array([ 0,  3, 12]), 5: array([6, 8]), 6: array([1]), 8: array([2, 7])}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文