【问题标题】:TypeError: '<' not supported between instances of 'str' and 'int' after converting string to floatTypeError:将字符串转换为浮点数后,“str”和“int”实例之间不支持“<”
【发布时间】:2022-01-19 15:42:27
【问题描述】:

使用:Google Collab 中的 Python 提前致谢: 我已经在我抓取 FBREF 的其他数据上运行了这段代码,所以我不确定为什么现在会发生这种情况。唯一的区别是我刮它的方式。 我第一次刮它: url_link = 'https://fbref.com/en/comps/Big5/gca/players/Big-5-European-Leagues-Stats'

第二次刮了:

url = 'https://fbref.com/en/comps/22/stats/Major-League-Soccer-Stats'

html_content = requests.get(url).text.replace('&lt;!--', '').replace('--&gt;', '')

df = pd.read_html(html_content)

然后我将数据从对象转换为浮点数,以便在将其拉入数据框后进行计算:

dfstandard['90s'] = dfstandard['90s'].astype(float) dfstandard['Gls'] = dfstandard['Gls'].astype(float)

我看了一下,发现它们都是花车:

10 90s 743 非空 float64

11 Gls 743 非空 float64

但是当我运行之前工作的代码时:

dfstandard['Gls'] = dfstandard['Gls'] / dfstandard['90s']

我收到错误消息“TypeError: '

我对抓取还很陌生,我被卡住了,不知道下一步该做什么。

完整的错误信息如下:

<ipython-input-152-e0ab76715b7d> in <module>()
      1 #turn data into p 90
----> 2 dfstandard['Gls'] = dfstandard['Gls'] / dfstandard['90s']
      3 dfstandard['Ast'] = dfstandard['Ast'] / dfstandard['90s']
      4 dfstandard['G-PK'] = dfstandard['G-PK'] / dfstandard['90s']
      5 dfstandard['PK'] = dfstandard['PK'] / dfstandard['90s']

8 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in _outer_indexer(self, left, right)
    261 
    262     def _outer_indexer(self, left, right):
--> 263         return libjoin.outer_join_indexer(left, right)```
    264 
    265     _typ = "index"

pandas/_libs/join.pyx in pandas._libs.join.outer_join_indexer()

TypeError: '<' not supported between instances of 'str' and 'int'>

【问题讨论】:

  • 请发布完整的错误信息回溯。
  • @JohnGordon 感谢您的评论。我将完整的错误消息添加到 OP 中。
  • 在完成此操作后,您能否包含一个数据框示例df = pd.read_html(html_content)
  • @Priya 对不起,我不是 100% 确定你的意思,所以我附上了一张图片。这是我使用的数据框的图片。我稍后会删除顶部的列标题。如果您需要其他东西,请告诉我。对不起,这个网站的新手。 drive.google.com/file/d/1m4qnPm94xuPt1ih3pFHmcnRzoouaHrzN/…
  • 我刚刚尝试过...我看到您有两个名为“Gls”的列?...您要使用哪一个?

标签: python web-scraping


【解决方案1】:

您的数据框中有两个 Gls 列。我认为您仅将一个 "Gls" 列转换为浮动,当您执行 dfstandard['Gls'] = dfstandard['Gls'] / dfstandard['90s'] 时,正在考虑另一个“Gls”列?...

也尝试从列名中去除空格

df = df.rename(columns=lambda x: x.strip())
df['90s'] = pd.to_numeric(df['90s'], errors='coerce')
df['Gls'] = pd.to_numeric(df['Gls'], errors='coerce')

因此错误。

【讨论】:

  • 我找到了一些代码来更改相同列的名称。 cols = [] count = 1 for column in dfstandard.columns: if column == 'Gls': cols.append(f'Gls_{count}') count+=1 continue cols.append(column) dfstandard.columns = cols 一旦我更改了计算以采用新名称,它就能够做到。 :)
  • 太棒了!..所以错误是正确的?
  • 是的,感谢您协助我寻找解决方案。我需要在某处点击解决吗?
  • 不,你不用随便点击,就说解决了。
猜你喜欢
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多