簡體   English   中英

如何從DataFrame的日期列中提取月份名稱和年份

[英]How to Extract Month Name and Year from Date column of DataFrame

我有以下 DF

45    2018-01-01
73    2018-02-08
74    2018-02-08
75    2018-02-08
76    2018-02-08

我想以以下格式以簡單的方式提取月份名稱和年份:

45    Jan-2018
73    Feb-2018
74    Feb-2018
75    Feb-2018
76    Feb-2018

我使用了返回"2018-01"格式的df.Date.dt.to_period("M")

將日期從對象轉換為實際日期時間並使用 dt 訪問您需要的內容。

import pandas as pd

df = pd.DataFrame({'Date':['2019-01-01','2019-02-08']})

df['Date'] = pd.to_datetime(df['Date'])

# You can format your date as you wish
df['Mon_Year'] = df['Date'].dt.strftime('%b-%Y')

# the result is object/string unlike `.dt.to_period('M')` that retains datetime data type.

print(df['Mon_Year'])

首先使用將列轉換為日期時間數據類型

sales_df['Date'] = pd.to_datetime(sales_df['Date'])

那么你可以做

sales_df['Month'] = sales_df['Date'].dt.month_name(locale='English')

暫無
暫無

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

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