Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list comprehension return a single value instead of a list

I have a column in a dataframe that consists of tuples shaped like this:

Prices
(0, 30.00)
(0, 20.00)
(0, 33.00)
(-12.00, 0)
(-13.00, 0)
(0,0)

I need to grab the non-zero values from each of the tuples if it exists and replace the tuple as a float in the column.

I used list comprehension, but it returns the value as a list instead of a float. Is there a better way to accomplish this? or an easy way to convert the list (of length 1) to a float?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am using python pandas

df['Prices'] = [[next((val for val in ls if val != 0), 0)] for ls in df['Prices'].values]

>Solution :

Your list comprehension creates an unnecessary inner list because that is what you wrote, you are unnecessarily wrapping that in a list. If you don’t want a list, don’t create the unnecessary list, so just next(...) instead of [next(...)]:

[next((val for val in ls if val != 0), 0)]

Should just be:

next((val for val in ls if val != 0), 0)

So:

df['Prices'] = [next((val for val in ls if val != 0), 0) for ls in df['Prices'].values]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading