将日期时间字段格式化为python pandas中的MON

编程入门 行业动态 更新时间:2024-10-12 03:18:01
将日期时间字段格式化为python pandas中的MON-YYYY并忽略空值(Format datetime field as MON-YYYY in python pandas & ignore nulls)

我有一个python pandas数据帧“df”如下 -

NAME SETID VENDOR_ID vendor_created_date 0 Vendor1 SD 93 2002-11-22 11:04:33 1 Vendor2 SD 94 2003-08-09 11:40:59 2 Service1 SD 95 2003-10-31 10:29:21 3 Vendor3 SD 01 NaT 4 Vendor4 SD 02 NaT

vendor_created_date的格式为datetime64[ns] 。

现在我想创建一个名为fomatted_date的新字段,其中vendor_created_date字段值应采用MON-YYYY格式,我想删除日期字段中带有NaT的行。

你能告诉我指示吗?

I have a python pandas dataframe "df" as below -

NAME SETID VENDOR_ID vendor_created_date 0 Vendor1 SD 93 2002-11-22 11:04:33 1 Vendor2 SD 94 2003-08-09 11:40:59 2 Service1 SD 95 2003-10-31 10:29:21 3 Vendor3 SD 01 NaT 4 Vendor4 SD 02 NaT

The vendor_created_date is of the format datetime64[ns].

Now I want to create a new field called fomatted_date where the vendor_created_date field values should be in the format MON-YYYY & I want to delete the rows with NaT in the date field.

Can you please give me directions?

最满意答案

这是你想要的格式吗?

基本上我们可以先删除NaN行,然后调用apply并使用datetime.strftime来应用新格式:

In [24]: df = df.dropna() df['fomatted_date'] = df['vendor_created_date'].apply(lambda x: dt.datetime.strftime(x,'%b-%Y')) df Out[24]: NAME SETID VENDOR_ID vendor_created_date fomatted_date Index 0 Vendor1 SD 93 2002-11-22 11:04:33 Nov-2002 1 Vendor2 SD 94 2003-08-09 11:40:59 Aug-2003 2 Service1 SD 95 2003-10-31 10:29:21 Oct-2003

is this the format you wanted?

Basically we can drop the NaN rows first and then call apply and use datetime.strftime to apply a new format:

In [24]: df = df.dropna() df['fomatted_date'] = df['vendor_created_date'].apply(lambda x: dt.datetime.strftime(x,'%b-%Y')) df Out[24]: NAME SETID VENDOR_ID vendor_created_date fomatted_date Index 0 Vendor1 SD 93 2002-11-22 11:04:33 Nov-2002 1 Vendor2 SD 94 2003-08-09 11:40:59 Aug-2003 2 Service1 SD 95 2003-10-31 10:29:21 Oct-2003

更多推荐

本文发布于:2023-08-04 10:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1413910.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   日期   格式   时间   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!