简体   繁体   English

NumPy - 在 nd 数组的每一列中查找和打印非零元素

[英]NumPy - Finding and printing non-zero elements in each column of a n-d array

Suppose I have the following Numpy nd array:假设我有以下 Numpy nd 数组:

array([[['a',0,0,0],
        [0,'b','c',0],
        ['e','d',0,0]]])

Now I would like to define 'double connections' of elements as follows:现在我想定义元素的“双重连接”,如下所示:

  1. We consider each column in this array as a time instant, and all elements in this instant are considered to happen at the same time.我们将此数组中的每一列视为一个时间瞬间,并且该瞬间中的所有元素都被认为是同时发生的。 0 means nothing happens. 0 表示什么都没有发生。 For example, a and e happens at the first time instant, b and d happens at the second time instant, and c itself happens in the third time instant.例如,a 和 e 发生在第一个时刻,b 和 d 发生在第二个时刻,c 本身发生在第三个时刻。
  2. If two elements, I believe it has 'double connections', and I would like to print the connections like this(if there is no such pair in one column, just move on to the next column until the end):如果有两个元素,我相信它有“双重连接”,我想打印这样的连接(如果一列中没有这样的对,则继续到下一列直到结束):
('a','e')
('e','a')
('b','d')
('d','b')

I tried to come up with solutions on iterating all the columns but did not work.Can anyone share some tips on this?我试图提出迭代所有列的解决方案,但没有奏效。有人可以分享一些关于此的提示吗?

You can recreate the original array by the following commands您可以通过以下命令重新创建原始数组

array = np.array([['a',0,0,0],
    [0,'b','c',0],
    ['e','d',0,0],dtype=object)

You could count how many non-zero elements you have for each column.您可以计算每列有多少个非零元素。 You select the columns with two non-zero elements, repeat them and inverse every second column:您选择具有两个非零元素的列,重复它们并每隔一列反转:

pairs = np.repeat(array[(array[:, (array != 0).sum(axis=0) == 2]).nonzero()].reshape((2, -1)).T, 2, axis=0)
pairs[1::2] = pairs[1::2, ::-1]

If you want to convert these to tuples like in your desired output you could just do a list comprehension:如果你想将这些转换为你想要的输出中的元组,你可以做一个列表理解:

output = [tuple(pair) for pair in pairs]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM