简体   繁体   中英

Remove NoneType from two lists

I'm working with two np.arrays of equal lengths. One of them contains None elements. I would like to remove these from that array and also from the corresponding elements in the other array.

Naively I thought this would do:

ToFRemove = (None == ListA)  # Find None type                          

ListA = ListA[not ToFRemove]
ListB = ListB[not ToFRemove]

This works for finding other regular elements. However, I get False as the value of ToFRemove so this does not work.

I assume I should write some iterator to find the elements that are None like in this answer but I don't know how.

I would do it like this

np_array[np_array != np.array(None)]

The statement np_array != np.array(None) outputs a boolean array. This boolean array would have 'False' where ever the element is of 'None' type and True for others. Indexes corresponding to 'True' remain in the resultant array and those corresponding to 'False' is removed.

Applying this to your problem

ToKeep = (ListA != np.array(None))
ListA = ListA[ToKeep]
ListB = ListA[ToKeep]
ToFRemove = np.array([x is None for x in ListA])

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