【问题标题】:Python setting the extracted Year-month in the Datetime formatPython将提取的年月设置为日期时间格式
【发布时间】: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


    【解决方案1】:

    你可以这样做:

    df['year-month'] = df.index.to_period('M')
    

    【讨论】:

    • 感谢您的快速回复。我的散点图在使用时抛出了错误。相反,这就是我所做的,它在散点图环境中工作。 pd.to_datetime(df.index.strftime('%Y-%m'))
    猜你喜欢
    • 2015-04-29
    • 2019-02-20
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多