[英]Converting a data frame with periods in an array of time-series with Pandas
我有这个问题,我正在尝试使用以下结构转换数据框(从具有数百万行的 CSV 文件加载):
| start | end | type | value |
|---------------------|---------------------|------|-------|
| 2016-01-01 00:00:00 | 2016-01-02 00:00:00 | 0 | 200 |
| 2016-01-02 01:00:00 | 2016-01-03 00:00:00 | 1 | 100 |
| 2016-01-15 08:00:00 | 2016-01-16 07:00:00 | 0 | 15 |
| 2016-01-16 07:00:00 | 2016-01-16 07:00:00 | 2 | 80 |
我想将其转换为具有以下格式的结构:
| timestamp | 0 | 1 | 2 |
|---------------------|-----|-----|---|
| 2016-01-01 00:00:00 | 200 | 0 | 0 |
| ... | 200 | 0 | 0 |
| 2016-01-02 00:00:00 | 200 | 0 | 0 |
| 2016-01-02 01:00:00 | 0 | 100 | 0 |
| ... | 0 | 100 | 0 |
| 2016-01-03 00:00:00 | 0 | 100 | 0 |
| ... | 0 | 0 | 0 |
| 2016-01-15 08:00:00 | 15 | 0 | 0 |
换句话说,虽然第一个表指定了 N type
事件的开始和结束时间段及其value
,但我希望最后有一个表,其中包含每个日期时间范围 a 包含所有值事件。
我试图找到一个有效的解决方案,我发现的最好的解决方案是基于从日期时间到整数的转换(使用自基准日期以来的小时数),然后使用此值作为numpy
数组的索引。 不幸的是,我的代码使用了 for 循环,我想知道您是否能想出更好的方法。
import pandas as pd
import numpy as np
# Example data frame
df = pd.DataFrame({'start': ['2016-01-01 00:00:00', '2016-01-02 01:00:00', '2016-01-15 08:00:00', '2016-01-16 07:00:00'],
'end': ['2016-01-02 00:00:00', '2016-01-03 00:00:00', '2016-01-16 07:00:00', '2016-01-16 07:00:00'],
'id': [0, 1, 0, 2],
'x': [200, 100, 15, 80]})
# Convert the strings in datetimes
df['start'] = pd.to_datetime(df['start'], format='%Y-%m-%d %H:%M:%S')
df['end'] = pd.to_datetime(df['end'], format='%Y-%m-%d %H:%M:%S')
# Get the date time offset
OFFSET = pd.datetime(2016, 1, 1, 0, 0, 0).timestamp() # this is the first date time I have
# Convert the dates in integers (conversion to nanoseconds and then to hours
df['start'] = ((df['start'].astype(np.int64) / (1e9) - OFFSET) / 3600).astype(np.int32) - 1
df['end'] = ((df['end'].astype(np.int64) / (1e9) - OFFSET) / 3600).astype(np.int32) - 1
# Target data structure
x = np.zeros((1000, 3)) # this must have a number of rows equal to the number of time stamps
# Put the data into the target structure
for i in range(0, 3):
x[df.iloc[i].start:df.iloc[i].end, df.iloc[i].id] = df.iloc[i].x
从日期时间到整数的转换是基于这个 SO question 。 我在 Python 方面的经验有限(我主要是 R 用户)然后我希望有一个更好(向量化?)和更优雅的解决方案。
先感谢您!
我将使用date_range
在新的列上创建的所有日期时间New
,然后用unnesting
和pivot_table
df['New']=[pd.date_range(x,y,freq='H') for x , y in zip(df.start,df.end)]
yourdf=unnesting(df,['New']).pivot_table(values='x',index='New',columns='id',aggfunc='sum',fill_value=0)
yourdf.head()
Out[327]:
id 0 1 2
New
2016-01-01 00:00:00 200 0 0
2016-01-01 01:00:00 200 0 0
2016-01-01 02:00:00 200 0 0
2016-01-01 03:00:00 200 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.