[英]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:现在我想定义元素的“双重连接”,如下所示:
('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.