熊猫Slinear插值按另一列分组

时间:2019-09-01 15:41:09

标签: python pandas interpolation

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

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

,但这未考虑不同的客户。在这种情况下我该如何分组?

1 个答案:

答案 0 :(得分:2)

IIUC,一旦您将set_index列中的日期设为日期,就可以在每个组的method='index'中使用interpolate,例如:

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