initialize pandas DataFrame with defined dtypes

2020-08-15 10:56发布

问题:

The pd.DataFrame docstring specifies a scalar argument for the whole dataframe:

dtype : dtype, default None Data type to force, otherwise infer

Seemingly it is indeed intended to be a scalar, as following leads to an error:

dfbinseq = pd.DataFrame([],
                        columns = ["chr", "centre", "seq_binary"],
                        dtype = ["O", pd.np.int64, "O"])

dfbinseq = pd.DataFrame([],
                        columns = ["chr", "centre", "seq_binary"],
                        dtype = [pd.np.object, pd.np.int64, pd.np.object])

The only workaround for creating an empty data frame (which I need to put in a HDF5 store for further appends) for me was

dfbinseq.centre.dtype = np.int64

Is there a way to set dtypes arguments at once?

回答1:

You can set dtype to Series:

import pandas as pd

df = pd.DataFrame({'A':pd.Series([], dtype='str'),
                   'B':pd.Series([], dtype='int'),
                   'C':pd.Series([], dtype='float')})

print (df)
Empty DataFrame
Columns: [A, B, C]
Index: []

print (df.dtypes)
A     object
B      int32
C    float64
dtype: object

With data:

df = pd.DataFrame({'A':pd.Series([1,2,3], dtype='str'),
                   'B':pd.Series([4,5,6], dtype='int'),
                   'C':pd.Series([7,8,9], dtype='float')})

print (df)
   A  B    C
0  1  4  7.0
1  2  5  8.0
2  3  6  9.0

print (df.dtypes)
A     object
B      int32
C    float64
dtype: object