Pandas 在 2 个给定数字之间进行插值,给定步长并在 groupby 内

Pandas interpolate between 2 given numbers, given step increase and within groupby

这是一个很复杂的问题,因为我可以找到其中每一个是如何单独完成的,但我想将它们放在一起,特别是在团体中应用。目标是使用 2 个值作为范围,并在给定设定间隔的情况下在它们之间插入值。接下来我想要一个带有 运行 总和的列(但是,我对此很熟悉。这是我在 groupby 中不理解的插值函数)。

如前所述,我从基础开始,效果很好,即:

df = pd.DataFrame({'minute':[1,3,4,5,8],'value':[1,4,7,10,13]})
max_value = df['minute'].max()

df.index = df.minute
df2 = pd.DataFrame({'minute':range(0,max_value), 'Value':0})
df2.index = df2.minute

df2.value = df.value
df2= df2.fillna(0)

但是现在给定一个额外的列,我如何将其应用于 'id' 'a'id 'h'

所以给定这个数据框:

df = pd.DataFrame([['a',    '0',    '10'],
                ['a',   '1',    '10'],
                ['h',   '2',    '15'],
                ['a',   '1',    '10'],
                ['h',   '3',    '20'],
                ['h',   '13',   '5']], columns = ['id','minute','value'])

我想生成此输出,它将按 id 列分组,按 minute 列插值,其中最小值为 0,最大值是该列中的最大值, 并在值栏中输入一个 0。

示例输出:

id  minute  value   sum
a   0        10     10
a   1        20     30
a   2         0     30
a   3         0     30
a   4         0     30
a   5         0     30
a   6         0     30
a   7         0     30
a   8         0     30
a   9         0     30
a   10        0     30
a   11        0     30
a   12        0     30
a   13        0     30
h   0         0      0
h   1         0      0
h   2        15     15
h   3        20     35
h   4         0     35
h   5         0     35
h   6         0     35
h   7         0     35
h   8         0     35
h   9         0     35
h   10        0     35
h   11        0     35
h   12        0     35
h   13        5     40

您可以尝试使用 from_product 方法创建一个 MultiIndex,然后用它重建索引。然后使用 groupby.cumsum 创建您的 'sum' 列:

min_idx = np.arange(df['minute'].max() + 1)
m_idx = pd.MultiIndex.from_product([df['id'].unique(), min_idx], names=['id', 'minute'])

df_new = df.set_index(['id', 'minute']).reindex(m_idx, fill_value=0).reset_index()
df_new['sum'] = df_new.groupby('id')['value'].cumsum()
df_new

[出局]

   id  minute  value  sum
0   a       0     10   10
1   a       1     10   20
2   a       2      0   20
3   a       3      0   20
4   a       4      0   20
5   a       5     10   30
6   a       6      0   30
7   a       7      0   30
8   a       8      0   30
9   a       9      0   30
10  a      10      0   30
11  a      11      0   30
12  a      12      0   30
13  a      13      0   30
14  h       0      0    0
15  h       1      0    0
16  h       2     15   15
17  h       3     20   35
18  h       4      0   35
19  h       5      0   35
20  h       6      0   35
21  h       7      0   35
22  h       8      0   35
23  h       9      0   35
24  h      10      0   35
25  h      11      0   35
26  h      12      0   35
27  h      13      5   40