【问题标题】:Python: Rearranging Dates in a specific column in excelPython:在excel的特定列中重新排列日期
【发布时间】:2020-05-26 12:00:47
【问题描述】:

我有一个 Excel 表,其中 F 列是日期列表。目前结构如下:

Year-Month-Day Hours:Mins:Secs

 - 2014-02-10 10:57:11
 - 2014-07-11 17:43:07
 - .... ect

我希望它是:

Month Date Year

 - Feb 11 2014
 - Jul 11 2014
 - .... ect

关于如何解决这个问题有什么建议吗?

加载 excel 文件 -> 仅编辑 F 列 -> 保存并用新列替换 F 列。

【问题讨论】:

    标签: python excel pandas dataframe


    【解决方案1】:

    使用dt.strftime

    #first cast column to pandas datetime.
    #df['ColumnF'] = pd.to_datetime(df['ColumnF'])
    df['ColumnG'] = df['ColumnF'].dt.strftime('%b %d %Y')
    
                  ColumnF      ColumnG
    0 2014-02-10 10:57:11  Feb 10 2014
    1 2014-07-11 17:43:07  Jul 11 2014
    

    解释。

    %b : 月份作为语言环境的缩写名称。

    %d:以零填充十进制数表示的月份中的日期。

    %Y : 年份,世纪为十进制数。

    【讨论】:

      【解决方案2】:
      import calendar 
      import pandas as pd
      
      ds = pd.read_excel("date.xlsx")# reads the data 
      ds["Date"] = pd.to_datetime(ds["colF"]) # converts datatype of column to datetime64[ns]
      ds['Date1'] = ds['Date'].dt.strftime("%B-%d-%Y") # converts months to month name 
      
      #if you want to replace with colF then 
      ds['colF']= ds['Date1']
      

      您可以关注类似的链接 python/pandas: convert month int to month name

      How to Extract Month Name and Year from Date column of DataFrame

      【讨论】:

      • 当我打印 Date1 时,它显示了我想要的,但它没有保存和替换旧的 ColF?
      • @ShawnAtlas Date1 是需要输出格式的新列,如果要替换旧的 colF ,直接使用 ds['colF'] = ds['Date'].dt.strftime( "%B-%d-%Y")。
      猜你喜欢
      • 2015-11-26
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多