简体   繁体   中英

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

Suppose I have the following Numpy nd array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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