合并间隔和时间戳数据帧

时间:2018-11-27 07:28:00

标签: python pandas dataframe aggregation

我有一个包含间隔的表

dfa = pd.DataFrame({'Start': [0, 101, 666], 'Stop': [100, 200, 1000]})

我还有另一个包含时间戳和值的表

dfb = pd.DataFrame({'Timestamp': [102, 145, 113], 'ValueA': [1, 2, 21],
'ValueB': [1, 2, 21]})

我需要创建一个与dfa相同大小的数据帧,并为{{1}中的所有行添加一列,其中包含ValueA / ValueB的某些聚合结果}},其中dfbTimestamp之间包含Start

所以在这里,如果将我的聚合定义为

Stop

我想要的输出将是:

{'ValueA':[np.nanmean,np.nanmin],
'ValueB':[np.nanmax]}

1 个答案:

答案 0 :(得分:1)

mergeassign创建的辅助列交叉连接使用:

d = {'ValueA':[np.nanmean,np.nanmin],
     'ValueB':[np.nanmax]}

df = dfa.assign(A=1).merge(dfb.assign(A=1), on='A', how='outer')

然后按StartStop进行过滤并按字典进行汇总:

df = (df[(df.Timestamp >= df.Start) & (df.Timestamp <= df.Stop)]
         .groupby(['Start','Stop']).agg(d))

使用mapjoin来平铺MultiIndex:

df.columns = df.columns.map('_'.join)
print (df)
            ValueA_nanmean  ValueA_nanmin  ValueB_nanmax
Start Stop                                              
101   200                8              1             21

最后join张原始照片:

df = dfa.join(df, on=['Start','Stop'])
print (df)
   Start  Stop  ValueA_nanmean  ValueA_nanmin  ValueB_nanmax
0      0   100             NaN            NaN            NaN
1    101   200             8.0            1.0           21.0
2    666  1000             NaN            NaN            NaN

编辑:

使用cut的解决方案:

d = {'ValueA':[np.nanmean,np.nanmin],
     'ValueB':[np.nanmax]}

#if not default index create it
dfa = dfa.reset_index(drop=True)
print (dfa)
   Start  Stop
0      0   100
1    101   200
2    666  1000

#add to bins first value of Start
bins = np.insert(dfa['Stop'].values, 0, dfa.loc[0, 'Start'])
print (bins)
[   0  100  200 1000]

#binning
dfb['id'] = pd.cut(dfb['Timestamp'], bins=bins, labels = dfa.index)
print (dfb)
   Timestamp  ValueA  ValueB id
0        102       1       1  1
1        145       2       2  1
2        113      21      21  1

#aggregate and flatten
df = dfb.groupby('id').agg(d)
df.columns = df.columns.map('_'.join)

#add to dfa
df = pd.concat([dfa, df], axis=1)
print (df)
   Start  Stop  ValueA_nanmean  ValueA_nanmin  ValueB_nanmax
0      0   100             NaN            NaN            NaN
1    101   200             8.0            1.0           21.0
2    666  1000             NaN            NaN            NaN