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?
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]