1

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.

6
  • actually does this work: [x for x in l if len(x)>0]? Commented Jan 20, 2016 at 12:11
  • Could you post code to create that list? Commented Jan 20, 2016 at 12:36
  • @AntonProtopopov I can't post the code because its a long function. Commented Jan 20, 2016 at 12:43
  • @AntonProtopopov I get this after slicing a dataframe by groupby and them I am appending it to the empty list. Commented Jan 20, 2016 at 12:45
  • 1
    Can you post raw data and code to reproduce your series, at the moment this is all very ambiguous Commented Jan 20, 2016 at 12:57

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

10 Comments

Yup, len(x)>0 is working and its removing empty series,but how can i convert the elements to the desired format
you mean [x.values.tolist() for x in l if len(x)>0]?
Yup. I ran [x.values.tolist() for x in l if len(x)>0] but its giving me error AttributeError: 'list' object has no attribute 'values'
Try that: [x.values.tolist() if type(x)==pd.Series else x for x in l if len(x) > 0]
@AntonProtopopov Thanks for your help. I ran what you suggested its giving me following output [x.values.tolist() if type(x)==pd.Series else x for x in DB if len(x) > 0] Out[482]: [[3 523 Name: order_id, dtype: object], [['526', '533']]]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.