![](/img/trans.png)
[英]ValueError: could not convert string to float: 'F' python
[英]ValueError: could not convert string to float: 'False' in python
我正在嘗試使用以下代碼從網頁中抓取表格數據,但出現錯誤:
ValueError: could not convert string to float: 'False'
in this line 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')
錯誤:
Traceback (most recent call last):
File "<ipython-input-128-30edd695db38>", line 15, in <module>
data = (tabulate(df[0], headers='keys', tablefmt='psql') )
File "D:\Conda\lib\site-packages\tabulate.py", line 1286, in tabulate
for c, ct, fl_fmt, miss_v in zip(cols, coltypes, float_formats, missing_vals)]
File "D:\Conda\lib\site-packages\tabulate.py", line 1286, in <listcomp>
for c, ct, fl_fmt, miss_v in zip(cols, coltypes, float_formats, missing_vals)]
File "D:\Conda\lib\site-packages\tabulate.py", line 1285, in <listcomp>
cols = [[_format(v, ct, fl_fmt, miss_v, has_invisible) for v in c]
File "D:\Conda\lib\site-packages\tabulate.py", line 754, in _format
return format(float(val), floatfmt)
ValueError: could not convert string to float: 'False'
該錯誤是不言自明的。 您不能將字符串'False'
轉換為float
。 你可以做的是迫使你的數據幀通過數字pd.to_numeric
,以替代不可兌換值NaN
,這是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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.