python - 如何更改 DataFrame 中一列的数据类型?

标签 python pandas dataframe

我想更改一个数据框列的数据类型(从 datetime64 到对象)。

首先,我创建数据框:

Python 2.6.8 (unknown, Jan 26 2013, 14:35:25) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> values = pd.Series(i for i in range(5))
>>> dates = pd.date_range('20130101',periods=5)
>>> df = pd.DataFrame({'values': values, 'dates': dates})
>>> df
/usr/local/lib/python2.6/dist-packages/pandas/core/config.py:570: DeprecationWarning: height has been deprecated.

  warnings.warn(d.msg, DeprecationWarning)
                dates  values
0 2013-01-01 00:00:00       0
1 2013-01-02 00:00:00       1
2 2013-01-03 00:00:00       2
3 2013-01-04 00:00:00       3
4 2013-01-05 00:00:00       4

它有两列:一列是 datetime64,另一列是 int64 dtype:

>>> df.dtypes
dates     datetime64[ns]
values             int64
dtype: object

在 pandas 文档中,我找到了如何将系列转换为任何数据类型。 它看起来像我需要的:

>>> df['dates'].astype(object)
0    2013-01-01 00:00:00
1    2013-01-02 00:00:00
2    2013-01-03 00:00:00
3    2013-01-04 00:00:00
4    2013-01-05 00:00:00
Name: dates, dtype: object

但是当我将这个系列指定为数据框列时,我又得到了一个 datetime64 dtype。

>>> df['dates'] = df['dates'].astype(object)
>>> df.dtypes
dates     datetime64[ns]
values             int64
dtype: object

请帮忙。如何将数据框的列转换为对象数据类型? 谢谢。

最佳答案

如果你真的想从 datetime64[ns] 的数据类型更改为对象,你可以运行这样的东西:

df['dates'] = df['dates'].apply(lambda x: str(x))
print df.types # Can verify to see that dates prints out as an object

关于python - 如何更改 DataFrame 中一列的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448153/

相关文章:

python - 提交元素不可点击 selenium python

python - 仅当条件为 True 时如何替换值?

python - 使用数组的 Seaborn fiddle 图 - 错误 : Neither the `x` nor `y` variable appears to be numeric

r - 根据列表值过滤数据框列

python - 将日期+小时转换为时间戳 - pandas/python

python - 没有支持的颜色终端库 Python/Jupyter

python - 如果另一列中的值为空,则删除重复项 - Pandas

python - Pandas 从另一个数据框中填充数据框中的缺失值

python - 将 DataFrame 过滤为具有 2 个以上 True 元素的行

python - Pandas 有条件创建数据框列 : based on multiple conditions max