【问题标题】:TypeError: unsupported operand type(s) for -: 'str' and 'float' comparing two dataframesTypeError: 不支持的操作数类型 -: 'str' 和 'float' 比较两个数据帧
【发布时间】:2019-01-22 05:21:10
【问题描述】:

假设有两个数据帧 - DF1DF2DF1 来自使用pandas.read_csv(path/to/file, header=1, index_col=[0]) 的.txt 逗号分隔文件,DF2 来自使用pandas.read_excel(path/to/file, header=0, index_col=[1]) 的.xlsx 文件。来自 file1 的 'header=1' 包含与 file2 中的 header=0 相同的列名,index_col=[0] 包含与 index_col=[1] 相同的对象名称。
我的目标是为每个对象(原始)减去每列的值。我正在尝试执行以下操作:

diff = df1 - df2

diff = pd.DataFrame.sub(df1,df2)

但它总是显示提到的错误:

TypeError: 不支持的操作数类型 -: 'str' 和 'float'

我做错了什么?

【问题讨论】:

  • 正如它所说的,一些单元格包含字符串,然后减去浮点数。你能提供你的df的例子吗
  • 只打印 if 语句之前的每个单元格。你会看到故障线。然后检查它是否浮动

标签: python excel pandas csv dataframe


【解决方案1】:

很可能,您的一个 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)

然后,减法将起作用。

【讨论】:

  • 乐于助人!请注意,对于您的具体示例,您可能希望使用 astype(float)
猜你喜欢
  • 2017-08-23
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
相关资源
最近更新 更多