如何在DataFrame中更改一列的dtype?

gho*_*hev 8 python dataframe pandas

我想更改一个数据框列的dtype(从datetime64到object).

首先,我创建数据框:

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
Run Code Online (Sandbox Code Playgroud)

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

>>> df.dtypes
dates     datetime64[ns]
values             int64
dtype: object
Run Code Online (Sandbox Code Playgroud)

在pandas文档中,我发现了如何将系列转换为任何dtypes.它看起来像我需要的:

>>> 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
Run Code Online (Sandbox Code Playgroud)

但是,当我将此系列分配为dataframe列时,我再次获得了datetime64 dtype.

>>> df['dates'] = df['dates'].astype(object)
>>> df.dtypes
dates     datetime64[ns]
values             int64
dtype: object
Run Code Online (Sandbox Code Playgroud)

请帮忙.如何将数据框的列转换为对象dtype?谢谢.

Wil*_*ill 5

如果您真的想从datetime64 [ns]的数据类型更改为object,则可以运行以下内容:

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


Jef*_*eff 0

这就是你所追求的吗?

In [9]: pd.pivot_table(data=df,rows='columns',cols='rows',values='values',margins=True).T
Out[9]: 
columns  2013-01-01 00:00:00  2013-01-02 00:00:00  2013-01-03 00:00:00  2013-01-04 00:00:00  2013-01-05 00:00:00       All
rows                                                                                                                      
a                          0                  NaN                    2                    3                  NaN  1.666667
b                        NaN                    1                  NaN                  NaN                    4  2.500000
All                        0                    1                    2                    3                    4  2.000000
Run Code Online (Sandbox Code Playgroud)