我有一个看起来像这样的数据集
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
带有日期的列,就可以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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句