【发布时间】:2021-03-18 20:29:05
【问题描述】:
我有一个带有日期时间格式索引的 df。我想提取每个样本的年月。稍后我将使用它为散点图中的样本着色。
我的代码:
df.index =
DatetimeIndex(['2019-10-01 08:16:57', '2019-10-01 08:43:54',
'2019-10-01 08:45:24', '2019-10-01 08:49:42',
'2019-10-01 09:01:04', '2019-10-01 09:07:04',
'2019-10-01 09:07:40', '2019-10-01 09:07:46',
'2019-10-01 09:14:09', '2019-10-01 09:14:57',
'2020-11-13 14:22:58', '2020-11-13 14:23:01',
'2020-11-13 14:31:40', '2020-11-13 14:31:58',
'2020-11-13 14:32:49', '2020-11-13 14:33:13',
'2020-11-13 14:36:16', '2020-11-13 14:40:03',
'2020-11-13 15:01:24', '2020-11-14 09:57:21'],
dtype='datetime64[ns]', name='timestamp', length=104676, freq=None)
df['year-month'] = df.index.strftime('%Y-%m')
print(df['year-month'])
Index(['2019-10', '2019-10', '2019-10', '2019-10', '2019-10', '2019-10',
'2019-10', '2019-10', '2019-10', '2019-10',
...
'2020-11', '2020-11', '2020-11', '2020-11', '2020-11', '2020-11',
'2020-11', '2020-11', '2020-11', '2020-11'],
dtype='object', name='timestamp', length=104676)
提取的 year-month 是对象类型,而不是 df.index 的日期时间类型。我想为 df 绘制散点图。我想根据它所属的年份和月份为样本着色。现在,当我设置 plt.scatter(x,y,c=df['year-month']) 时,它会引发错误。因此,将其转换为时间戳格式可以解决散点图问题。
【问题讨论】:
标签: python pandas datetime matplotlib