Skip to main content
 首页 » 编程设计

python之在 Pandas 中创建 DateTimeIndex

2025年05月04日15java哥

我第一次用panda,遇到困难

我有一个数据框,在单独的列中包含年、月、日和小时。

据我所知,此数据框未编入索引。

我正在尝试为此数据框创建一个日期时间索引:

def createTimeStamp(year, month, day, hour):  
    return DatetimeIndex(datetime(.........)) 
 
df['TimeStamp'] = df.apply(createTimeStamp(df['year'], df['month'], df['day'], df['hour'])) 
 
df.set_index('TimeStamp') 

我做错了什么?

请您参考如下方法:

import datetime as dt 
import pandas as pd 
 
df = pd.DataFrame({'year': [2015, 2016],  
                   'month': [12, 1],  
                   'day': [31, 1],  
                   'hour': [23, 1]}) 
 
# returns datetime objects 
df['Timestamp'] = df.apply(lambda row: dt.datetime(row.year, row.month, row.day, row.hour),  
                           axis=1) 
 
# converts to pandas timestamps if desired 
df['Timestamp'] = pd.to_datetime(df.Timestamp) 
 
>>> df 
   day  hour  month  year           Timestamp 
0   31    23     12  2015 2015-12-31 23:00:00 
1    1     1      1  2016 2016-01-01 01:00:00 
 
# Create a DatetimeIndex and assign it to the dataframe. 
df.index = pd.DatetimeIndex(df.Timestamp) 
 
>>> df 
                     day  hour  month  year           Timestamp 
2015-12-31 23:00:00   31    23     12  2015 2015-12-31 23:00:00 
2016-01-01 01:00:00    1     1      1  2016 2016-01-01 01:00:00