我有以下代码行:
open_tks_per_day['Created_year_month'] = pd.to_datetime(open_tks_per_day['Created']).dt.to_period('M')
这样做是从日期时间中提取年和月,并将其存储在名为Created_year_month的列中。问题是此列是一个对象,但是当我尝试使用以下代码将其转换为日期时间时:
open_tks_per_day['Created_year_month'] = open_tks_per_day['Created_year_month'].astype('datetime64')
我收到以下错误:
TypeError: <class 'pandas._libs.tslibs.period.Period'> is not convertible to datetime
这样做的全部目的是能够使用带状图将Created_year_month
变量相对于分类变量进行绘制,就好像我使用整个日期对它进行绘制一样,我得到了太多的数据点,所以我发现如果按月和年汇总数据点,我得到的数据点会减少,这会使我的表象看起来更整洁。
以下是一些示例数据:
Number Created Created_date Created_year_month
2018-01-16 16:23:21 2018-01-16 2018-01
2018-01-11 17:51:18 2018-01-11 2018-01
2018-01-12 13:03:50 2018-01-12 2018-01
2018-01-11 13:28:55 2018-01-11 2018-01
2018-01-04 09:58:36 2018-01-04 2018-01
2018-01-23 09:19:36 2018-01-23 2018-01
2019-04-09 10:50:54 2019-04-09 2019-04
2019-04-08 19:22:49 2019-04-08 2019-04
2019-04-09 12:34:24 2019-04-09 2019-04
2019-04-09 17:22:10 2019-04-09 2019-04
2019-04-09 09:58:52 2019-04-09 2019-04
2019-04-08 20:08:01 2019-04-08 2019-04
2019-04-09 18:40:13 2019-04-09 2019-04
2019-04-09 19:29:04 2019-04-09 2019-04
2019-04-10 02:43:15 2019-04-10 2019-04
2019-04-10 03:04:36 2019-04-10 2019-04
2019-04-10 03:12:02 2019-04-10 2019-04
2019-04-10 03:49:19 2019-04-10 2019-04
2019-04-10 04:46:04 2019-04-10 2019-04
2019-04-10 05:18:24 2019-04-10 2019-04
答案 0 :(得分:0)
问题是因为时间段与日期时间不同。在您的问题中,我不确定您想要什么输出。例如,是按月,总和,均值等对对象进行计数吗?无论如何,pandas.Grouper都有一个可以帮助您的内置功能。</ p>
假设:我假设您想要每天的开放票数。我还假设您可以计算一些字段。如果没有,您可以随时添加open_tks_per_day['is_ticket'] = 1
。在本示例的其余部分中,我将使用is_ticket
作为您要计数的东西。
假设您想按月计算未清票数,则可以执行以下操作:
res = open_tks_per_day['Created'].groupby(Grouper(key='Created', freq='M')).count().reset_index()
plt.plot(res['Created'],res['is_ticket']) # Again making assumptions here
免责声明:没有示例数据,因此我无法测试我的代码。