【问题标题】:Fastest way to transpose time ranges to time matrix将时间范围转置为时间矩阵的最快方法
【发布时间】: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


    【解决方案1】:

    FROMTO 之间创建日期时间的秒范围,通过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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多