Accessing the first item of list values that occur irregularly in a Pandas column

Viewed 2565

I have a pandas dataframe and in one of the columns a list value appears in some of the values. I need to be able to extract the first item of the list, if it's a list, and if it's not a list then the value will be unchanged. I am struggling to achieve it using the lambda function:

df1 = pd.DataFrame({'Fruits':['Apple',['Banana',6],'Kiwi','Cheese']})

df1['Fruits'] = df1['Fruits'].apply(lambda(x): x[0] if (type(x) == 'list') else x) 

If I use the above the column remains unchanged. I am guessing this must be a problem with the conditional statement within the lambda function....

I would also be interested if there is a better way of achieving this within Pandas.

1 Answers
Related