【问题标题】:How to Extract Month Name and Year from Date column of DataFrame如何从 DataFrame 的日期列中提取月份名称和年份
【发布时间】:2019-07-15 05:27:01
【问题描述】:

我有以下 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

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

【问题讨论】:

  • 所以你想把top df格式转换成bottom df?

标签: python pandas dataframe datetime


【解决方案1】:

将您的日期从对象转换为实际日期时间,并使用 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'])

【讨论】:

  • 我认为你不需要dt之前的年份和列?
  • 我相信你会的。投射df['Date].dt.year` 后显示年份。您拥有来自 dt 的所有日期时间函数,如月、日、周数等
  • 我得到了我想要的价值。但是,自从它返回字符串值以来,对 Date [用于绘图和其他用途] 进行排序已成为一个问题。
  • 是的,这就是为什么使用.dt.to_period。你用什么工具来绘图?
  • 我正在使用“seaborn”
【解决方案2】:

首先使用将列转换为日期时间数据类型

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

那你就可以了

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

【讨论】:

  • 请格式化您的代码以提高可读性。 (使用 Ctrl.+K)
猜你喜欢
  • 2015-05-23
  • 2021-10-02
  • 2018-02-16
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多