PythonPandas - 用不同的PeriodIndex频率连接2个DataFrames。

问题描述 投票:0回答:1

我想用不同的PeriodIndex频率连接2个DataFrames,并使用第二级索引即位置进行排序。

例如,我有以下2个DataFrames。

import pandas as pd

pr1h = pd.period_range(start='2020-01-01 08:00', end='2020-01-01 11:00', freq='1h')
pr2h = pd.period_range(start='2020-01-01 08:00', end='2020-01-01 11:00', freq='2h')

n_array_1h = [2, 2, 2, 2]
n_array_2h = [0, 1, 0, 1]

index_labels_1h = [pr1h, n_array_1h]
index_labels_2h = [[pr2h[0],pr2h[0],pr2h[1],pr2h[1]], n_array_2h]

values_1h = [[1], [2], [3], [4]]
values_2h = [[10], [20], [30], [40]]

df1h = pd.DataFrame(values_1h, index=index_labels_1h, columns=['Data'])
df1h.index.names=['Period','Position']
df2h = pd.DataFrame(values_2h, index=index_labels_2h, columns=['Data'])
df2h.index.names=['Period','Position']

df1h
                           Data
Period           Position      
2020-01-01 08:00 2            1
2020-01-01 09:00 2            2
2020-01-01 10:00 2            3
2020-01-01 11:00 2            4

df2h
                       Data
Period           Position      
2020-01-01 08:00 0           10
                 1           20
2020-01-01 10:00 0           30
                 1           40

我想得到df1h_new,它。

  • 保持 df1h 的 PeriodIndex。
  • 将数据块中的数据保存在df2h中,其period.start_time的时间比df1h中的当前perdiod.start_time的时间小或等于。
  • 显然,保留了df1h的数据

所以结果会是。

df1h_new
                           Data
Period           Position      
2020-01-01 08:00 0           10  # |---> data coming from df2h, block with
                 1           20  # |     start_time =< df1h.index[0].start_time
                 2            1  # ----> data from df1h.index[0]
2020-01-01 09:00 0           10  # |---> data coming from df2h, block with 
                 1           20  # |     start_time =< df1h.index[1].start_time
                 2            2  # ----> data from df1h.index[1]
2020-01-01 10:00 0           30  # and so on...
                 1           40
                 2            3
2020-01-01 11:00 0           30
                 1           40
                 2            4

请问,有什么推荐的方法可以实现呢?感谢您的帮助和支持! Bests,

python pandas concat
1个回答
1
投票

一个想法是使用 concatSeries.unstack 并将频率改为相同的 Series.asfreq,然后回填错误的值,并重新塑形回。MultiIndex:

df = (pd.concat([df1h['Data'].unstack(),
                 df2h['Data'].unstack().asfreq('H')], axis=1)
        .bfill()
        .stack()
        .sort_index()
        .to_frame('Data'))
print (df)
                           Data
Period           Position      
2020-01-01 08:00 0         10.0
                 1         20.0
                 2          1.0
2020-01-01 09:00 0         10.0
                 1         20.0
                 2          2.0
2020-01-01 10:00 0         30.0
                 1         40.0
                 2          3.0
2020-01-01 11:00 0         30.0
                 1         40.0
                 2          4.0
© www.soinside.com 2019 - 2024. All rights reserved.