在 Pandas DataFrame 中存储纯 python datetime.datetime

max*_*max 6 python datetime python-3.x pandas

由于matplotlib不支持任何pandas.TimeStamp 或者numpy.datetime64,有没有简单的解决办法,我决定到本地大熊猫日期列转换为纯Python datetime.datetime,这样散点图更容易做出。

然而:

t = pd.DataFrame({'date': [pd.to_datetime('2012-12-31')]})
t.dtypes # date    datetime64[ns], as expected
pure_python_datetime_array = t.date.dt.to_pydatetime() # works fine
t['date'] = pure_python_datetime_array # doesn't do what I hoped
t.dtypes # date    datetime64[ns] as before, no luck changing it
Run Code Online (Sandbox Code Playgroud)

我猜大熊猫自动转换纯Pythondatetime所生产to_pydatetime到其原生格式。我想这通常是方便的行为,但有没有办法覆盖它?

Neh*_*ani 4

to_pydatetime()的使用是正确的。

In [87]: t = pd.DataFrame({'date': [pd.to_datetime('2012-12-31'), pd.to_datetime('2013-12-31')]})

In [88]: t.date.dt.to_pydatetime()
Out[88]: 
array([datetime.datetime(2012, 12, 31, 0, 0),
       datetime.datetime(2013, 12, 31, 0, 0)], dtype=object)
Run Code Online (Sandbox Code Playgroud)

当您将其分配回 时t.date,它会自动将其转换回datetime64

pandas.Timestamp无论如何都是日期时间子类:)

绘制该图的一种方法是将日期时间转换为 int64:

In [117]: t = pd.DataFrame({'date': [pd.to_datetime('2012-12-31'), pd.to_datetime('2013-12-31')], 'sample_data': [1, 2]})

In [118]: t['date_int'] = t.date.astype(np.int64)

In [119]: t
Out[119]: 
        date  sample_data             date_int
0 2012-12-31            1  1356912000000000000
1 2013-12-31            2  1388448000000000000

In [120]: t.plot(kind='scatter', x='date_int', y='sample_data')
Out[120]: <matplotlib.axes._subplots.AxesSubplot at 0x7f3c852662d0>

In [121]: plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

另一个解决方法是(不使用分散,但是......):

In [126]: t.plot(x='date', y='sample_data', style='.')
Out[126]: <matplotlib.axes._subplots.AxesSubplot at 0x7f3c850f5750>
Run Code Online (Sandbox Code Playgroud)

并且,最后的解决办法:

In [141]: import matplotlib.pyplot as plt

In [142]: t = pd.DataFrame({'date': [pd.to_datetime('2012-12-31'), pd.to_datetime('2013-12-31')], 'sample_data': [100, 20000]})

In [143]: t
Out[143]: 
        date  sample_data
0 2012-12-31          100
1 2013-12-31        20000
In [144]: plt.scatter(t.date.dt.to_pydatetime()  , t.sample_data)
Out[144]: <matplotlib.collections.PathCollection at 0x7f3c84a10510>

In [145]: plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这在github上有一个问题,目前已开放。