Neil
Neil

Reputation: 8247

how to remove empty series from list in Python

I have a list which looks something like this.

DB
Out[469]: 
[[3    523
Name: order_id, dtype: object], 0    [526, 533]
Name: order_id, dtype: object, Series([], Name: order_id, dtype: object)]

And what I want it to look like this.

DB
[['523',['526','533']]]

I am doing following in python

 DB[0][0].values[0]
 Out[462]: '523'

 DB[1][0]
 Out[463]: ['526', '533']

And to remove empty series

 [x for x in DB if x != []]   

But It doesn't work. I want a for loop which will iterate through DB and give me final output. Please help.

Upvotes: 1

Views: 486

Answers (1)

EdChum
EdChum

Reputation: 393863

test for the len inside your list comprehension to remove it:

In [150]:
l=[pd.Series(['asda']), pd.Series(), pd.Series([9,12,4])]
l

Out[150]:
[0    asda
 dtype: object, Series([], dtype: float64), 0     9
 1    12
 2     4
 dtype: int64]

In [153]:    
[x for x in l if len(x)>0]

Out[153]:
[0    asda
 dtype: object, 0     9
 1    12
 2     4
 dtype: int64]

You can see that the lengths are different:

In [155]:
print(len(l))
print(len([x for x in l if len(x)>0]))

3
2

Upvotes: 2

Related Questions