假设这是我的多级 DataFrame:
States = pd.DataFrame({'Alaska' : [1, 2, 3, 4], 'Arizona': [5, 6, 7, 8]},
index=pd.MultiIndex(levels=[['A', 'B'], ['x','y']],
labels=[[1,1,0,0],[1,0,1,0]])).T
我正在尝试从此 DataFrame 派生新变量。
def scoring_algorithm(x):
return x[('A', 'x')] + 100
States.apply(scoring_algorithm)
但这会引发错误
KeyError: (('A', 'x'), '发生在索引 (B, y)')
我从错误中假设我的列选择器 ('A', 'x')
不令人满意,但我找不到任何资源来了解如何将其用于应用函数。
注意:我需要 apply 函数或类似的函数,因为最终的评分算法需要几列作为 apply 函数的输入。
预先感谢您的指导!
最佳答案
您当前正在申请索引。
df.apply(fxn)
相当于:
df.apply(fxn, axis='index')
您需要应用到列。
df.apply(fxn, axis='columns')
所以对你来说:
States.apply(scoring_algorithm, axis='columns')
我得到:
Alaska 104
Arizona 108
dtype: int64
关于python - 在多级 DataFrame 上使用 pandas apply 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42704615/