如何创建数据框?

时间:2015-04-06 09:59:15

标签: python pandas dataframe

缺货[21]:

日期

2012-04-12 14:56:50    1.25640
2012-04-12 15:11:55    1.43075
2012-04-12 15:27:01    1.36991
2012-04-12 15:42:06    1.35935
2012-04-12 15:57:10    1.30568
2012-04-12 16:12:10    1.28775
2012-04-12 16:27:14    1.24597
2012-04-12 16:42:19    1.28228
2012-04-12 16:57:24    1.36571
2012-04-12 17:12:28    1.32013
2012-04-12 17:27:33    1.35489
2012-04-12 17:42:37    1.34368
2012-04-12 17:57:41    1.31422
2012-04-12 18:12:44    1.31197
2012-04-12 18:27:46    1.33898
...
2014-04-15 14:14:59    5.40786
2014-04-15 14:29:59    5.43847
2014-04-15 14:44:59    5.48222
2014-04-15 14:59:59    5.49327
2014-04-15 15:14:59    5.42679
2014-04-15 15:29:59    5.43036
2014-04-15 15:44:59    5.41471
2014-04-15 15:59:59    5.47004
2014-04-15 16:14:59    5.47507
2014-04-15 16:29:59    5.55595
2014-04-15 16:44:59    5.46151
2014-04-15 16:59:59    5.52125
2014-04-15 17:14:59    5.44116
2014-04-15 17:29:59    5.35836
2014-04-15 17:44:59    5.29439

名称:千瓦时,长度:65701

我有这个数据框,我想创建另外3个包含年,月和时间的数据框。我如何创建?

1 个答案:

答案 0 :(得分:0)

让我们创建一个虚拟数据,如

start = datetime.datetime(2000, 1, 1)
end = datetime.datetime(2000, 1, 3)
d = pd.date_range(start, end, freq='H')
t_df = pd.DataFrame({'col1': np.random.random_integers(0, 10, d.size)}, index=d)

t_df

                   col1
2000-01-01 00:00:00 4
2000-01-01 01:00:00 8
2000-01-01 02:00:00 2
2000-01-01 03:00:00 3
2000-01-01 04:00:00 0
2000-01-01 05:00:00 1
2000-01-01 06:00:00 0
2000-01-01 07:00:00 10

现在,提取日期属性

t_df['year'] = t_df.index.year
t_df['month'] = t_df.index.month
t_df['day'] = t_df.index.day
t_df

                  col1  year  month day
2000-01-01 00:00:00 4   2000    1   1
2000-01-01 01:00:00 8   2000    1   1
2000-01-01 02:00:00 2   2000    1   1
2000-01-01 03:00:00 3   2000    1   1
2000-01-01 04:00:00 0   2000    1   1
2000-01-01 05:00:00 1   2000    1   1
2000-01-01 06:00:00 0   2000    1   1
2000-01-01 07:00:00 10  2000    1   1

详细了解DatetimeIndex