I have a 2 dimensional numpy array and want to remove all 'false' values. A nested array with different lengths should be created.
[['false' 'value1' 'false' 'false' 'value5' 'false' 'false' 'false'
'false' 'false' 'false' 'false' 'false' 'false' 'false' 'false']
['false' 'value1' 'false' 'false' 'false' 'false' 'false' 'false'
'false' 'value10' 'value11' 'false' 'false' 'false' 'false'
'false']]
I would like to get:
[['value1' 'value5']
['value1' 'value10' 'value11']]
CodePudding user response:
You should make use of the filter() built-in-function
>>> an_array = ['false', 'a', 'b', 'c', 'false']
>>> filtered_array = list(filter(lambda a: a != 'false', an_array))
['a', 'b', 'c']
CodePudding user response:
you cant have different lengths in a numpy array but you can make it into a 2d array and then just sort the values like this:
arr = [['false', 'value1', 'false', 'false', 'value5', 'false', 'false', 'false',
'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false'],
['false', 'value1', 'false', 'false', 'false', 'false', 'false', 'false',
'false', 'value10', 'value11', 'false', 'false', 'false', 'false',
'false']]
List1 = []
List2 = []
for x in arr:
for char in x:
if char != "false" and x == arr[0]:
List1.append(char)
elif char != "false" and x == arr[1]:
List2.append(char)
print(List1)
print(List2)
and then you get 2 lists that dont contain the false values.
CodePudding user response:
You need to iterated for each list in your lists and then apply the filter function and append a new list with this output
lists = [['false', 'value1', 'false', 'false', 'value5', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false'],
['false', 'value1', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'value10', 'value11', 'false', 'false', 'false', 'false', 'false']]
filtered_list = []
for x in lists:
filtered_list.append(list(filter(lambda a: a!="false", x)))
filtered_list
in the filtered_list var you will get the output