【问题标题】:How to calculate slope in rows of a multiindex dataframe in pandas?如何计算熊猫中多索引数据框的行中的斜率?
【发布时间】:2021-08-28 03:35:18
【问题描述】:

我有这个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索引xy之间的斜率,以便得到:

  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.xs吗?我不知道multiindex df是如何工作的。

slope = (y2-y1)/(x2-x1)

【问题讨论】:

    标签: python pandas dataframe indexing multi-level


    【解决方案1】:
    • 使用shift 作为np.roll() 表示x2A 位置C 的值
    • 您对 COb1 斜率的采样数据似乎不正确
    • 您的问题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,
      ('Ob2', 'x'): 36.33},
     'B': {('Ob1', 'y'): 2.15,
      ('Ob1', 'x'): 47.8,
      ('Ob2', 'y'): 2.34,
      ('Ob2', 'x'): 47.8},
     'C': {('Ob1', 'y'): 2.29,
      ('Ob1', 'x'): 460.2,
      ('Ob2', 'y'): 2.57,
      ('Ob2', '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, [0, -1])
    dfs = pd.concat(
        [
            df,
            pd.DataFrame(
                shift((y2 - y1) / (x2 - x1), [0, 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
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2017-12-05
      • 1970-01-01
      • 2021-12-19
      • 2018-03-28
      • 2016-05-20
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      相关资源
      最近更新 更多