如何计算pandas中多索引数据帧行的斜率? 输出

问题描述

我有这个 df 样本:

  Name  Cords   A      B    C
  Ob1     y    4.95  2.15  2.29
          x   36.33  47.8  460.2   
  Ob2     y    1.22  2.34  2.57
          x   36.33  47.8  460.2 

其中"Name"是索引,"Cords"是二级索引,即多索引DataFrame,但是现在我想计算de index x和{{1}之间的斜率}}为了得到:

y

我必须使用 Name Cords A B C Ob1 y 4.95 2.15 2.29 x 36.33 47.8 460.2 slope 0 -0.24 3.39 Ob2 y 1.22 2.34 2.57 x 36.33 47.8 460.2 slope 0 0.09 5.57e-4 吗?,我不知道多索引 df 究竟是如何工作的。

df.xs

解决方法

  • 使用 shift 作为 np.roll() 表示 x2C 在位置 A
  • 的值
  • 看起来您的采样数据对于 C
  • Ob1 斜率不正确
  • 您的问题 multi-index slicing 已被使用 .loc
from scipy.ndimage.interpolation import shift

df = pd.DataFrame({'A': {('Ob1','y'): 4.95,('Ob1','x'): 36.33,('Ob2','y'): 1.22,'x'): 36.33},'B': {('Ob1','y'): 2.15,'x'): 47.8,'y'): 2.34,'x'): 47.8},'C': {('Ob1','y'): 2.29,'x'): 460.2,'y'): 2.57,'x'): 460.2}})

x1 = df.loc[(slice(None),"x"),:].values
y1 = df.loc[(slice(None),"y"),:].values
x2 = shift(x1,[0,-1])
y2 = shift(y1,-1])
dfs = pd.concat(
    [
        df,pd.DataFrame(
            shift((y2 - y1) / (x2 - x1),1]),columns=df.columns,index=pd.MultiIndex.from_product(
                [df.index.get_level_values(0).unique(),["slope"]]
            ),),]
).sort_index()

输出

               A          B           C
Ob1 slope   0.00  -0.244115    0.000339
    x      36.33  47.800000  460.200000
    y       4.95   2.150000    2.290000
Ob2 slope   0.00   0.097646    0.000558
    x      36.33  47.800000  460.200000
    y       1.22   2.340000    2.570000