简体   繁体   English

熊猫更改列日期格式

[英]Pandas Change column date format

I have column in pandas dataframe as follows: 我在pandas数据框中有如下列:

0    2018-04-06
1    2018-04-06
2    2018-04-09
3    2018-04-19
4    2018-04-19
5    2018-04-17

I want to convert this column into yyyy/mm/dd for which I have coaded as follows: 我想将此列转换为yyyy / mm / dd,如下所示:

def change_date_format(x):
    if x != 'nan' and x != '' and x != ' ' and x != 0:
        x = parse(x, dayfirst=True).strftime("%Y-%m-%d")
        return x
    else:
        return ''

read4['Column Name'] = read4['Column Name'].apply(lambda x : change_date_format(x)  )

But it's convert as follows: 但是它的转换如下:

2018-06-04
2018-06-04
2018-09-04
2018-04-19
2018-04-19
2018-04-17

which ideally should be : 理想情况下应该是:

2018-04-06
2018-04-06
2018-04-09
2018-04-19
2018-04-19
2018-04-17

How do I force it do work as above. 我如何强制它按上述方式工作。 Basically it should consider the input also and depends on that it should work. 基本上,它还应该考虑输入,并取决于它应该起作用。

I think need to_datetime with parameter errors='coerce' for convert not parseable values to NaT , then strftime and last replace : 我认为需要to_datetime并将参数errors='coerce'用于将不可解析的值NaTNaT ,然后是strftime和最后一次replace

read4['Column Name'] = (pd.to_datetime(read4['Column Name'], errors='coerce')
                          .dt.strftime("%Y-%m-%d")
                          .replace('NaT', ''))
  Column Name
0  2018-04-06
1  2018-04-06
2  2018-04-09
3  2018-04-19
4  2018-04-19
5  2018-04-17

也许您需要将您的dayfirst标志设置为False

x = parse(x, dayfirst=False).strftime("%Y-%m-%d")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM