Skip to main content
 首页 » 编程设计

python之将时间范围转置为时间矩阵的最快方法

2024年11月24日9lautakyan007

我正在尝试将具有特定值 (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 

请您参考如下方法:

在 FROM 和 TO 之间创建日期时间的秒范围,通过 DataFrame.join 添加列 X, Y最后一次使用 DataFrame.pivot :

df1['FROM'] = pd.to_datetime(df1['FROM']) 
df1['TO'] = pd.to_datetime(df1['TO']) 
 
df2 = pd.concat([pd.Series(r.Index,pd.date_range(r.FROM, r.TO, freq='s'))  
                 for r in df1.itertuples()]).reset_index() 
df2.columns = ['Date','Val'] 
df2 = df2.join(df1[['X','Y']], on='Val').pivot('Date','X','Y')