如何生成新的Pandas专栏,将测量结果与下周五进行比较

时间:2016-10-15 03:10:53

标签: pandas

我有一只像这样的大熊猫MultiIndex

                         Inj  time  
date       SID                                  
2016-10-11 ABC003S801    PBS    30        
           ABC003S802    PBS    12           
           ABC003S803    PBS    52         
           ABC003S804    PBS    19           
...
2016-10-12 ABC003S801    PBS    27           
           ABC003S802    PBS     5            
           ABC003S803    PBS    11             
           ABC003S804    PBS     7             
...
2016-10-14 ABC003S801    PBS    10           
           ABC003S802    PBS     3            
           ABC003S803    PBS     4            
           ABC003S804    PBS     5            
...

我想创建一个新列,这是现有列(例如time)与下周五之间的差异。

例如,上述数据2016-10-112016-10-12应与下周五2016-10-14 - df['new_column'] = df.time - df.time_next_friday 进行比较:

                         Inj  time  new_column
date       SID                                  
2016-10-11 ABC003S801    PBS    30          20               
           ABC003S802    PBS    12           9 
           ABC003S803    PBS    52          48
           ABC003S804    PBS    19          14
...
2016-10-12 ABC003S801    PBS    27          17 
           ABC003S802    PBS     5           2
           ABC003S803    PBS    11           7
           ABC003S804    PBS     7           2 
...
2016-10-14 ABC003S801    PBS    10           0
           ABC003S802    PBS     3           0 
           ABC003S803    PBS     4           0 
           ABC003S804    PBS     5           0 
...

请注意,差异应该在具有相应SID值的行之间。

2 个答案:

答案 0 :(得分:1)

第一个交换日期和SID索引级别,因为它将在以后回填时有用:

df = df.swaplevel().sort_index()

星期五将通过这个布尔索引找到:

fridays = df.index.get_level_values(1).dayofweek==4

现在,您可以通过回填值将星期五数据与每行对齐来执行操作,然后执行减法:

df['delta_vs_friday'] = df.time - df.time.where(fridays).bfill()

如果需要,请重新调整等级。

答案 1 :(得分:0)

考虑pd.DataFrame df和索引tidx

tidx = pd.date_range('2016-03-31', periods=23, freq='D')
df = pd.DataFrame(np.arange(23) ** 2, tidx, ['A'])

然后以下是下周五的值的数据框

df.groupby(df.index.weekday.__eq__(5).cumsum()).transform('last')

enter image description here