【问题标题】:How to Convert Datetime column header (e.g. 2007-03-01 00:00:00) into Date-Month-Year format i.e. 2007-03-01如何将日期时间列标题(例如 2007-03-01 00:00:00)转换为日期-月-年格式,即 2007-03-01
【发布时间】:2019-02-16 15:44:20
【问题描述】:

如何将日期时间列标题(例如 2007-03-01 00:00:00)转换为日期-月-年格式,即 2007-03-01?

我试过了

df=pd.DataFrame({'Company Name':['3M India Ltd.','A B B India Ltd.'],'2007-03-01 00:00:00':[1571.30,710.20],'2007-04-01 00:00:00':[710.20,818.13]})
df.columns=pd.to_datetime.date(df.columns) 

但显示错误 AttributeError: 'function' object has no attribute 'date'

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    首先通过set_index 创建index,而不是日期时间列,然后使用to_datetime 并在必要时使用dates 添加DatetimeIndex.date

    df = df.set_index('Company Name')
    df.columns = pd.to_datetime(df.columns).date
    print (df)
                      2007-03-01  2007-04-01
    Company Name                            
    3M India Ltd.         1571.3      710.20
    A B B India Ltd.       710.2      818.13
    

    另一种解决方案,如果不可能,第一个解决方案可以通过columns 创建Series,然后使用errors='coerce' 调用to_datetime 将所有值从列转换为日期时间,因为不返回日期NaT(缺少日期时间的值),所以最后添加 fillna 以将非日期时间替换为原始列名:

    s = pd.Series(df.columns)
    df.columns = pd.to_datetime(s, errors='coerce').dt.date.fillna(s)
    print (df)
           Company Name  2007-03-01  2007-04-01
    0     3M India Ltd.      1571.3      710.20
    1  A B B India Ltd.       710.2      818.13
    

    详情

    print (pd.to_datetime(s, errors='coerce'))
    0          NaT
    1   2007-03-01
    2   2007-04-01
    dtype: datetime64[ns]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多