我有一个看起来像这样的数据集
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
关于python - Pandas 线性插值按另一列分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57747376/