gpt4 book ai didi

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'float' comparing two dataframes

转载 作者:行者123 更新时间:2023-12-04 22:32:15 25 4
gpt4 key购买 nike

假设有两个数据帧 - DF1DF2 .DF1来自 .txt 逗号分隔文件,使用 pandas.read_csv(path/to/file, header=1, index_col=[0])DF2来自 .xlsx 文件,使用 pandas.read_excel(path/to/file, header=0, index_col=[1]) . 'header=1'来自 file1 的列名与 header=0 相同在文件 2 和 index_col=[0] 中包含与 index_col=[1] 相同的对象名称.
我的目标是为每个对象(原始)减去每列的值。我正在尝试执行以下操作:
diff = df1 - df2
或者
diff = pd.DataFrame.sub(df1,df2)
但它总是显示提到的错误:

TypeError: unsupported operand type(s) for -: 'str' and 'float'



我做错了什么?

最佳答案

很可能,您的 DataFrame 之一包含字符串,而另一个包含数字。

例如,如果我写

df1 = pd.DataFrame([1,2,3])
df2 = pd.DataFrame(['3', '2', '6'])
df1 - df2

然后我得到
TypeError: unsupported operand type(s) for -: 'int' and 'str'

要修复它,我可以添加该行
df2 = df2.astype(int)

然后,减法将起作用。

关于python - 类型错误 : unsupported operand type(s) for -: 'str' and 'float' comparing two dataframes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51856875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com