我有一个类似这样的数据集
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'
,例如:相关问题 更多 >
编程相关推荐