为何用+运算符相加DataFrame多索引列得NaN,.add(axis=1)却正常?
多级列索引DataFrame列相加出错问题
我有一个带多级行索引(year/month)和多级列索引的DataFrame,结构如下:
Tiered Rates Prices lower higher year month 2022 11 41.36 0.00 12 74.42 0.00 2023 1 72.31 0.00 2 71.01 0.00
尝试用+运算符直接相加lower和higher两列时,执行代码:
monthly_pivot[('Tiered Rates Prices', 'higher')] + monthly_pivot[('Tiered Rates Prices', 'lower')]
出现错误提示:
Expected a one-dimensional object, got a DataFrame with 2 columns instead.
打印结果得到全NaN的DataFrame,不符合预期:
Tiered Rates Prices higher lower year month 2022 11 NaN NaN 12 NaN NaN 2023 1 NaN NaN 2 NaN NaN
但使用行求和的方式可以得到正确结果:
monthly_pivot['Tiered Rates Prices'].sum(axis=1)
结果:
year month 2022 11 82.72 12 148.84 2023 1 144.62 2 142.02
问题原因
你的DataFrame列是两级MultiIndex,第一级为Tiered Rates Prices,第二级为lower/higher。直接使用monthly_pivot[('Tiered Rates Prices', 'higher')]并没有正确获取到单列Series,反而因为索引匹配问题返回了包含lower和higher两列的子DataFrame。两个DataFrame相加时,列对齐逻辑无法匹配对应数据,最终返回全NaN。
正确的列相加方式
需要明确获取到单个Series后再相加,以下几种方式都可行:
- 使用
loc精准定位列:
monthly_pivot.loc[:, ('Tiered Rates Prices', 'lower')] + monthly_pivot.loc[:, ('Tiered Rates Prices', 'higher')]
- 先取第一级列的子DataFrame,再提取第二级列:
monthly_pivot['Tiered Rates Prices']['lower'] + monthly_pivot['Tiered Rates Prices']['higher']
- 使用
xs方法提取指定层级的列:
monthly_pivot.xs('lower', level=1, axis=1) + monthly_pivot.xs('higher', level=1, axis=1)
以上方式都能得到和sum(axis=1)一致的结果。
内容的提问来源于stack exchange,提问作者Long Vuong
相关产品推荐
相关产品推荐

