在python中将datetime字段格式化为MON-YYYY(&;忽略空值
我有一个数据帧“df”,如下所示-在python中将datetime字段格式化为MON-YYYY(&;忽略空值,python,python-3.x,pandas,pandasql,Python,Python 3.x,Pandas,Pandasql,我有一个数据帧“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
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
创建的供应商日期的格式为datetime64[ns]
现在我想创建一个名为fomatted_date
的新字段,其中vendor_created_date
字段值的格式应为MON-yyyyy
&我想删除日期字段中带有NaT
的行
你能告诉我怎么走吗 这是您想要的格式吗 基本上,我们可以先删除
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
这是你想要的格式吗 基本上,我们可以先删除
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
有几种方法可以做到这一点 一种方法是使用正则表达式(
re
module)搜索已知模式,并用所需的输出替换它
另一种方法是使用
datetime
模块,并使用datetime.datetime.strftime将其转换为所需格式。有几种方法
一种方法是使用正则表达式(re
module)搜索已知模式,并用所需的输出替换它
另一种方法是使用
datetime
模块,并使用datetime.datetime.strftime将其转换为所需的格式。为什么这里有标记?你也在寻找R中的解决方案吗?不管怎样,我现在正在取消标记。为什么这里有一个标记?你也在寻找R中的解决方案吗?不管怎样,我现在正在取消标记。