python - Pandas 线性插值按另一列分组

标签 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

但这并没有考虑到不同的客户。对于这种情况我该如何进行分组?

最佳答案

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/

相关文章:

python - 将 Pandas DataFrame 写入以换行符分隔的 JSON

python - 在python中将.txt文件转换为整数矩阵

python - 通过对自身执行计算从 1dim numpy 数组创建 numpy 矩阵?

python - Python Pandas 中的 Groupby/Sum - 零计数不显示......有时

python - 从连续日期时间变量创建分类变量

python - 如何为 "scipy.interpolate.make_lsq_spline"选择好的结序列

r - 插值/将向量中的值拉伸(stretch)到指定长度

python - 有谁知道如何在 Python 中执行双三次样条插值?

python - Django:如何在勾选清除复选框时自动从存储中删除文件?

Python 导入模块但启动时无法识别它?