在 Pandas 中创建 DateTimeIndex

gui*_*cgs 3 python datetime pandas

我第一次使用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')
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Ale*_*der 10

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
Run Code Online (Sandbox Code Playgroud)


Col*_*rik 5

问题是 set_index 修改了 DataFrame 的副本。如果您将 inplace=True 传递给 set_index ,原始数据帧将被更新。或者,如果需要更多操作,可以重新分配 DataFrame

df.set_index('TimeStamp', inplace=True)
或者
df = df.set_index('TimeStamp')