簡體   English   中英

Python 將提取的年月設置為日期時間格式

[英]Python setting the extracted Year-month in the Datetime format

我有一個帶有日期時間格式索引的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是 object 類型,而不是日期時間類型,如 df.index。 我想為 df 分散 plot 的 plot。 我想根據它所屬的年份和月份為樣本着色。 現在,當我設置plt.scatter(x,y,c=df['year-month'])時,它會引發錯誤。 因此,將其轉換為時間戳格式可以解決分散 plot 問題。

你可以做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM