pandas 如何将列设置为日期索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37610983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:43:11  来源:igfitidea点击:

how set column as date index?

pandasdataframetimedelta

提问by bikuser

My data sets looks like:

我的数据集看起来像:

       Date    Value
    1/1/1988    0.62
    1/2/1988    0.64
    1/3/1988    0.65
    1/4/1988    0.66
    1/5/1988    0.67
    1/6/1988    0.66
    1/7/1988    0.64
    1/8/1988    0.66
    1/9/1988    0.65
    1/10/1988   0.65
    1/11/1988   0.64
    1/12/1988   0.66
    1/13/1988   0.67
    1/14/1988   0.66
    1/15/1988   0.65
    1/16/1988   0.64
    1/17/1988   0.62
    1/18/1988   0.64
    1/19/1988   0.62
    1/20/1988   0.62
    1/21/1988   0.64
    1/22/1988   0.62
    1/23/1988   0.60

I used this code to read this data

我用这段代码来读取这些数据

df.set_index(df['Date'], drop=False, append=False, inplace=False, verify_integrity=False).drop('Date', 1)

but the problem is index is not in date format. So the question is how to set this column as date index?

但问题是索引不是日期格式。所以问题是如何将此列设置为日期索引?

回答by EdChum

Your question lacked a proper explanation, but you can do the following:

您的问题缺乏正确的解释,但您可以执行以下操作:

In [75]:
# convert to datetime
df['Date'] = pd.to_datetime(df['Date'])
df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 23 entries, 0 to 22
Data columns (total 2 columns):
Date     23 non-null datetime64[ns]
Value    23 non-null float64
dtypes: datetime64[ns](1), float64(1)
memory usage: 448.0 bytes

In [76]:
# set the index
df.set_index('Date', inplace=True)
df.info()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 23 entries, 1988-01-01 to 1988-01-23
Data columns (total 1 columns):
Value    23 non-null float64
dtypes: float64(1)
memory usage: 368.0 bytes

So here to_datetimewill convert date strings to datetimedtype, set_indexwith param inplace=Trueis all you need,

所以这里to_datetime将日期字符串转换为datetimedtype,你只需要set_indexparam inplace=True