Pandas DataFrame将多种类型转换为列 [英] Pandas DataFrame cast multiple types to columns

查看:592
本文介绍了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)

但这有两个问题:

  1. 很乱
  2. 看起来它涉及不必要的复制操作-在大型数据集上这可能会很昂贵.

推荐答案

或者,您可以通过首先创建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

这篇关于Pandas DataFrame将多种类型转换为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆