【发布时间】:2019-04-30 09:44:06
【问题描述】:
我正在尝试将具有特定值 (df1) 的时间值范围转换为基于第二频率索引 (df2) 的矩阵。
目前我正在迭代第一个数据帧并使用 loc 函数将值转置到第二个数据帧中的多行,但我认为这是一种缓慢的方法,因为迭代速度非常慢。
def create_columns(df):
x = list(dict.fromkeys(df['X']))
return x
date_rng = pd.date_range(start=df1.iloc[0]['FROM'], end=df1.iloc[-1]['TO'], freq='s')
cols = create_columns(df1)
df2 = pd.DataFrame(columns = [cols], index = date_rng)
for index, row in df1.iterrows():
date_rng = pd.date_range(start=row['FROM'], end=row['TO'], freq='s')
df2.loc[date_rng, row['X']] = row['Y']
基础 df1:
X FROM TO Y
0 A 01/01/2019 00:00:00 01/01/2019 00:00:09 1
1 B 01/01/2019 00:00:05 01/01/2019 00:00:14 1
2 A 01/01/2019 00:00:10 01/01/2019 00:00:30 0
3 B 01/01/2019 00:00:15 01/01/2019 00:00:40 0
4 C 01/01/2019 00:00:00 01/01/2019 00:01:00 0
结果 df2:
A B C
01/01/2019 00:00:00 1 1 0
01/01/2019 00:00:01 1 1 0
01/01/2019 00:00:02 1 1 0
01/01/2019 00:00:03 1 1 0
01/01/2019 00:00:04 1 1 0
01/01/2019 00:00:05 1 1 0
01/01/2019 00:00:06 1 1 0
01/01/2019 00:00:07 1 1 0
01/01/2019 00:00:08 1 1 0
01/01/2019 00:00:09 1 1 0
01/01/2019 00:00:10 1 0 0
01/01/2019 00:00:11 1 0 0
01/01/2019 00:00:12 1 0 0
【问题讨论】:
标签: python pandas time-series