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

Apply function to all the elements (lists of strings) of a column to convert into floats

My dataframe df has a column ‘c’ of lists of strings. For example the first element is df.loc['index_0','c'] = ['10', ' 20'].

I want to convert all the elements in the lists into floats. For example the first element of df should be df.loc['index_0','c'] = [10.0, 20.0].

I know how to do it for one list at a time using list(map(float, df.loc['index_0','c'])).

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 would like to do it for all the lists and I tried this: df['c'].apply(lambda x: list(map(float, x))) but I get an error: ‘float’ object is not iterable

>Solution :

I think the error is due to the presence of NaN values in the column c, one way to fix this is to remove the NaN values before applying the map function:

df['c'] = df['c'].dropna().apply(lambda x: list(map(float, x)))
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