ValueError:无法将字符串转换为float:python中的“False”

2024-06-03 03:11:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用以下代码从网页中获取表数据,但出现错误:

ValueError: could not convert string to float: 'False'在这一行data = (tabulate(df[0], headers='keys', tablefmt='psql') )

import pandas as pd
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate

res = requests.get("http://rerait.telangana.gov.in/PrintPreview/PrintPreview/UHJvamVjdElEPTQmRGl2aXNpb249MSZVc2VySUQ9MjAyODcmUm9sZUlEPTEmQXBwSUQ9NSZBY3Rpb249U0VBUkNIJkNoYXJhY3RlckQ9MjImRXh0QXBwSUQ9")
soup = BeautifulSoup(res.content,'html.parser')

table_data = []

for i in range(len(soup.find_all('table'))):

    table = soup.find_all('table')[i] 
    df = pd.read_html(str(table))
    data = (tabulate(df[0], headers='keys', tablefmt='psql') )
    print (data)

df_1 = pd.DataFrame(data)
df_1.to_csv('D:/out_table.csv')

错误:

^{pr2}$

Tags: tofromimportdfdata错误tablekeys
1条回答
网友
1楼 · 发布于 2024-06-03 03:11:58

这个错误是不言而喻的。不能将字符串'False'转换为float。您可以通过^{}强制数据帧为数值,用^{cd4>}替换不可转换的值,即float

dfs = pd.read_html(str(table))
dfs[0] = dfs[0].iloc[:].apply(pd.to_numeric, errors='coerce')
data = tabulate(dfs[0], headers='keys', tablefmt='psql')

相关问题 更多 >