Reputation: 465
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.
Upvotes: 1
Views: 875
Reputation: 15364
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})
Upvotes: 1
Reputation: 120409
Or use pd.to_numeric
:
df = pd.DataFrame(A).apply(pd.to_numeric)
>>> df
0 1 2
0 1 5.4 2
1 2 6.0 3
>>> df.dtypes
0 int64
1 float64
2 int64
dtype: object
If you have non numeric columns, use:
pd.DataFrame(A).apply(pd.to_numeric, errors='ignore')
Upvotes: 1
Reputation: 71570
You could use applymap
with pd.eval
:
>>> df = pd.DataFrame(A).applymap(pd.eval)
>>> df
0 1 2
0 1 5.4 2
1 2 6.0 3
>>> df.dtypes
0 int64
1 float64
2 int64
dtype: object
>>>
Upvotes: 1