I have a numpy array A which looks like this:
JavaScript
x
5
1
array([list(['nan', 'nan']),
2
list(['nan', 'nan', 'apple', 'apple', 'banana', 'nan', 'nan']),
3
list(['red', 'red']), ,
4
list(['nan', 'festival'])], dtype=object)
5
I want to convert this to an array in which each list contains only unique elements. For example, I want the above array to get converted to:
JavaScript
1
2
1
['nan'],['nan','apple','banana'],['red'], ,['nan','festival']
2
I have tried doing this:
JavaScript
1
5
1
output = []
2
for i in A:
3
output.append(np.unique(i))
4
output
5
The output which I get doing this is not desired and currently looks like this:
JavaScript
1
4
1
[array(['nan'], dtype='<U3'),
2
array(['nan'], dtype='<U3'),
3
array(['nan'], dtype='<U3'), .]
4
What can be done?
Advertisement
Answer
JavaScript
1
5
1
arr=np.array([list(['nan', 'nan']),
2
list(['nan', 'nan', 'apple', 'apple', 'banana', 'nan', 'nan']),
3
list(['red', 'red']), ,
4
list(['nan', 'festival'])], dtype=object)
5
try via list comprehension:
JavaScript
1
2
1
out=[np.unique(x).tolist() for x in arr]
2
OR
JavaScript
1
2
1
out=[list(np.unique(x)) for x in arr]
2
output of out
:
JavaScript
1
2
1
[['nan'], ['apple', 'banana', 'nan'], ['red'], [Ellipsis], ['festival', 'nan']]
2