Pandas 数据框中两列的差异

Difference of two columns in Pandas dataframe

嗨,我试图从 Excel 中获取两列并解析为 DataFrame,之后我需要减去这些列。

这是我的代码

ndf = xw.Range('AI1:AJ' + str(len(last_row))).options(pd.DataFrame).value

#Error in this line below
ndf['VC-BC'] = ndf['VC'] - ndf['BC']

#xw.Range("BH1").options(index=False).value = ndf

print(ndf.head(20))

交叉 post 在 : https://python-forum.io/Thread-Difference-of-two-columns-in-Pandas-dataframe

让它起作用的一个建议是将条件 index=False 添加到 options 函数。

ndf = xw.Range('AI1:AJ' + str(len(last_row))).options(pd.DataFrame, index=False).value

xw 已将您的列 VC 解析为索引,这导致 KeyError 当您尝试对该列进行操作时。