【问题标题】:How can I undo a time series conversion of a pandas dataframe?如何撤消熊猫数据框的时间序列转换?
【发布时间】:2019-05-14 21:38:06
【问题描述】:

我将数据帧的索引设置为时间序列:

new_data.index = pd.DatetimeIndex(new_data.index)}

如何将此时间序列数据转换回原始字符串格式?

【问题讨论】:

    标签: python pandas datetime indexing


    【解决方案1】:

    Pandas 索引对象通常具有与系列可用的方法等效的方法。这里可以使用pd.Index.astype

    df = pd.DataFrame(index=['2018-01-01', '2018-05-15', '2018-12-25'])
    
    df.index = pd.DatetimeIndex(df.index)
    # DatetimeIndex(['2018-01-01', '2018-05-15', '2018-12-25'],
    #               dtype='datetime64[ns]', freq=None)
    
    df.index = df.index.astype(str)
    # Index(['2018-01-01', '2018-05-15', '2018-12-25'], dtype='object')
    

    Pandas 中的注释字符串存储在object dtype 系列中。如果您需要特定格式,这也可以提供:

    df.index = df.index.strftime('%d-%b-%Y')
    # Index(['01-Jan-2018', '15-May-2018', '25-Dec-2018'], dtype='object')
    

    有关约定,请参阅Python's strftime directives

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 1970-01-01
      • 2018-07-13
      • 2015-04-24
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多