Skip to content
Advertisement

convert list of strings to panda dataframe with types

I have a list of a list of numbers where two rows are strings, e.g.

A = [[1,’5.4′,’2′],[2,’6′,’3′]]

How do I convert this to a pandas dataframe, such that the 1st and 3nd columns are integers and the 2nd column is a float

by

pd.DataFrame(A,dtype=float)

it converts all to floats.

Advertisement

Answer

Here is a possible solution:

pd.DataFrame(A).astype({0: int, 1: float, 2: int})

If you don’t want to convert everything to a string and then change the type you could do something like this (everything is loaded as a float and then later you change the dtype of a few columns to int):

pd.DataFrame(A, dtype=float).convert_dtypes()

or

pd.DataFrame(A, dtype=float).astype({0: int, 2: int})
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement