组内线性插值

3 投票
1 回答
547 浏览
提问于 2025-04-18 06:25

假设我有一个多重索引的数据表 df,里面有一列 A。我想创建一个新列 B,在这个新列中,我会把每组 A 中的最低值赋值为 m(比如说 0),把最高值赋值为 M(比如说 1),而中间的值则通过线性插值来填充。

举个例子,看看下面这个 df。我想对每个 X 组进行插值处理。

                     A 
X      Y                              
bar   one    -0.007381 
      two    -1.219794 
baz   one     0.145578 
      two    -0.249321 
      three  -0.249321 
      four    0.21     
foo   one    -1.046479 
      two     1.314373 
qux   one     0.716789 
      two     0.385795 

我觉得可以用 Pandas 中的 aggregatetransform 这两个功能来实现,但我不太确定具体该怎么做。

1 个回答

2

我觉得如果你用 groupby 可能会更好,而不是用 multiIndex

数据:

X      Y    A                          
bar   one    -0.007381 
bar   two    -1.219794 
baz   one     0.145578 
baz   two    -0.249321 
baz   three  -0.249321 
baz   four    0.21     
foo   one    -1.046479 
foo   two     1.314373 
qux   one     0.716789 
qux   two     0.385795 

还有:

In [47]:

df['new']=df.groupby(df.X).transform(lambda x: (x - x.min()) / x.ptp()).A
print df
     X      Y         A       new
0  bar    one -0.007381  1.000000
1  bar    two -1.219794  0.000000
2  baz    one  0.145578  0.859745
3  baz    two -0.249321  0.000000
4  baz  three -0.249321  0.000000
5  baz   four  0.210000  1.000000
6  foo    one -1.046479  0.000000
7  foo    two  1.314373  1.000000
8  qux    one  0.716789  1.000000
9  qux    two  0.385795  0.000000

[10 rows x 4 columns]

撰写回答