如何为pandas分层MultiIndex DataFrame计算并填充Slope斜率列
解决方案
完整可运行实现代码
import pandas as pd import numpy as np # 构建测试用多层索引DataFrame df = pd.DataFrame({('Number', 1): {('A', 'Blue', 'One', 'Bar'): 1, ('A', 'Blue', 'Two', 'Foo'): 2}, ('Number', 2): {('A', 'Blue', 'One', 'Bar'): 2, ('A', 'Blue', 'Two', 'Foo'): 4}, ('Number', 3): {('A', 'Blue', 'One', 'Bar'): 3, ('A', 'Blue', 'Two', 'Foo'): 6}, ('Slope', ''): np.nan}) # 初始化Slope列为空值 # 提取Number层级下的二级列名作为x数组 x = df['Number'].columns.astype(int).to_numpy() # 定义单行列斜率计算函数,采用一阶线性拟合取斜率值 def calc_row_slope(row): y = row.values return np.polyfit(x, y, deg=1)[0] # 对所有行的Number列分组应用计算,结果写入Slope列 df[('Slope', '')] = df['Number'].apply(calc_row_slope, axis=1)
运行后输出的df和你示例中的目标结果完全一致。
缺失值兼容优化
如果你的数据存在空值,可以调整斜率计算函数自动过滤空值,避免计算报错:
def calc_row_slope(row): # 过滤当前行的空值位置 not_na_mask = ~row.isna() y_filter = row[not_na_mask].values x_filter = x[not_na_mask] # 有效点数小于2时无法计算斜率,返回空值 if len(x_filter) < 2: return np.nan return np.polyfit(x_filter, y_filter, deg=1)[0]
内容的提问来源于stack exchange,提问作者The Nightman
相关产品推荐
相关产品推荐

