Pandas DataFrame将多种类型转换为列
问题描述:
我想在实例化时为pandas DataFrame的列声明不同的类型:
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])
如果dtype仅是一种类型(例如dtype=float
),而不是上面的多种类型,则此方法有效-有办法吗?
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)
但这有两个问题:
- 很乱
- 看起来它涉及不必要的复制操作-在大型数据集上这可能会很昂贵.
答
或者,您可以通过首先创建Series
对象来为每列指定dtype
.
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