Python Pandas – How to Cast Multiple Types to DataFrame Columns

pandaspython

I'd like to declare different types for the columns of a pandas DataFrame at instantiation:

frame = pandas.DataFrame({..some data..},dtype=[str,int,int])

This works if dtype is only one type (e.g dtype=float), but not multiple types as above – is there a way to do this?

The common solution seems to be to cast later:

frame['some column'] = frame['some column'].astype(float)

but this has a couple of issues:

  1. It's messy
  2. Looks like it involves an unnecessary copy operation – this could be expensive on large data sets.

Best Answer

As an alternative, you can specify the dtype for each column by creating the Series objects first.

In [2]: df = pd.DataFrame({'x': pd.Series(['1.0', '2.0', '3.0'], dtype=float), 'y': pd.Series(['1', '2', '3'], dtype=int)})

In [3]: df
Out[3]: 
   x  y
0  1  1
1  2  2
2  3  3

[3 rows x 2 columns]

In [4]: df.dtypes
Out[4]: 
x    float64
y      int64
dtype: object
Related Question