【问题标题】:How can I format datetime with na in python 3 pandas如何在 python 3 pandas 中用 na 格式化日期时间
【发布时间】:2018-04-06 09:05:41
【问题描述】:

我在熊猫日期表中有 NA:

0    2017-04-04 00:00:00
1    2018-09-20 00:00:00
2    na
3    2018-09-01 00:00:00
4    na
5    2018-01-01 00:00:00

我需要把表格改成不带时间的字符串类型,日期格式用点分隔,na替换为空字符串''

0    04.04.2017
1    20.09.2018
2    
3    01.09.2018
4    
5    01.01.2018

如果我使用 strftime('%d.%m.%Y') 我收到错误。 如果我使用 dt.date 它会给我错误的格式:2017-04-04

【问题讨论】:

    标签: python string pandas date formatting


    【解决方案1】:

    使用strftime,但替换NaTs 使用replace

    #if necessary
    #df['col'] = pd.to_datetime(df['col'])
    df = df['col'].dt.strftime('%d.%m.%Y').replace('NaT','')
    print (df)
    0    04.04.2017
    1    20.09.2018
    2              
    3    01.09.2018
    4              
    5    01.01.2018
    Name: col, dtype: object
    

    【讨论】:

      【解决方案2】:

      你在正确的轨道上!请注意,调用 fillna 会将列转换为非日期时间类型。但转换后可以拨打str.replace

      df['date'].dt.date.fillna('')\
           .astype(str).str.split('-').str[::-1].str.join('.')
      
      0    04.04.2017
      1    20.09.2018
      2              
      3    01.09.2018
      4              
      5    01.01.2018
      Name: date, dtype: object
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-07
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多