Pandas 按另一列分组的线性插值

Pandas Slinear Interpolation grouping by another column

我有一个看起来像这样的数据集

testing = pd.DataFrame({'col':[1,np.nan,np.nan,7,1,np.nan,np.nan,7], 
                        'col2':['01-MAY-17 15:47:00','01-MAY-17 15:57:00',
                            '07-MAY-17 15:47:00','07-MAY-17 22:07:00',
                            '01-MAY-17 15:47:00','01-MAY-17 15:57:00',
                            '07-MAY-17 15:47:00','07-MAY-17 22:07:00'],
                        'Customer_id':['A','A','A','A','B','B','B','B']})

我需要根据每个客户在第一列中插入缺失值(在这种情况下,这不会有什么不同,但因为我有一些客户,他们的第一个或最后一个都有缺失值,我真的需要把它分开)。

之前,我用的是这个:

testing.groupby('Customer_id').apply(lambda group: group.interpolate(method= 'linear'))

但这假设每个点都是等距的,因为第二列是每条记录被收集的日期时间,所以可以看出它不是。

为了以考虑不同间距的方式进行更改,我将 col2 传递给索引,并使用 slinear

进行插值
testing['col2'] = pd.to_datetime(testing['col2'])
testing['index1'] = testing.index
testing = testing.set_index('col2')
testing.apply(lambda group: group.interpolate(method= 'slinear'))
test_int=testing.interpolate(method='slinear')
test_int['col2'] = test_int.index
test_int = test_int.set_index('index1')
test_int

但这并没有考虑到不同的客户。这种情况怎么分组?

IIUC,一旦你有了 set_index 带日期的列,你就可以在每个组的 interpolate 中使用 method='index',例如:

testing.col2 = pd.to_datetime(testing.col2)
print (testing.set_index('col2').groupby('Customer_id')
              .apply(lambda x: x.interpolate(method= 'index')).reset_index())
                 col2       col Customer_id
0 2017-05-01 15:47:00  1.000000           A
1 2017-05-01 15:57:00  1.006652           A
2 2017-05-07 15:47:00  6.747228           A
3 2017-05-07 22:07:00  7.000000           A
4 2017-05-01 15:47:00  1.000000           B
5 2017-05-01 15:57:00  1.006652           B
6 2017-05-07 15:47:00  6.747228           B
7 2017-05-07 22:07:00  7.000000           B