简体   繁体   English

如何将 dataframe 中的列转换为索引日期时间 object?

[英]How to convert a column in a dataframe to an index datetime object?

I have a question about how to convert a column 'Timestamp' into an index&datetime.我有一个关于如何将列“时间戳”转换为索引和日期时间的问题。 And then also drop the column once it's converted into an index.然后在将列转换为索引后也将其删除。

df = {'Timestamp':['20/01/2021 01:00:00.12 AM','20/01/2021 01:00:00.21 AM','20/01/2021 01:00:01.34 AM], 
      'Value':['14','178','158','75']} 

I tried the following, but obvious didn't work.我尝试了以下方法,但显然没有用。

df.Timestamp = pd.to_datetime(df.Timestamp.str[0])
df=df.set_index(['Timestamp'], drop=True)

FYI.供参考。 The df is actually a lot text processing so unfortunately I cannot just do read_csv and parse datetime object. df 实际上是很多文本处理,所以不幸的是我不能只做 read_csv 和解析日期时间 object。 :( So yes, the df is exactly as what's prescribed above. :( 所以是的,df 完全符合上面的规定。

Thank you.谢谢你。

Don't enclose 'Timestamp' in square brackets.不要将“时间戳”括在方括号中。

import pandas as pd

df = pd.DataFrame({'Timestamp':['20/01/2021 01:00:00.12 AM','20/01/2021 01:00:00.21 AM','20/01/2021 01:00:01.34 AM'], 
      'Value':['14','178','158']})

df['Timestamp'] = pd.to_datetime(df['Timestamp'])

df = df.set_index('Timestamp')
  
print(df)

## Output

                          Value
Timestamp
20/01/2021 01:00:00.12 AM    14
20/01/2021 01:00:00.21 AM   178
20/01/2021 01:00:01.34 AM   158

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM