Pandas DataFrame cast multiple types to columns

pandas, python

Solution

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

Problem

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: - It's messy - Looks like it involves an unnecessary copy operation - this could be expensive on large data sets.

Original source