Python 如何将html表转换为dataframe
Python 如何将html表转换为dataframe,python,dataframe,pandas,html-table,Python,Dataframe,Pandas,Html Table,pandas提供了一个有用的to_html()转换DataFrame到html表中。是否有任何有用的函数将其读回数据帧?在一般情况下,这是不可能的,但如果您大致了解表的结构,您可以这样做: # Create a test df: >>> df = DataFrame(np.random.rand(4,5), columns = list('abcde')) >>> df a b c d
pandas
提供了一个有用的to_html()
转换DataFrame
到html表中。是否有任何有用的函数将其读回数据帧?在一般情况下,这是不可能的,但如果您大致了解表的结构,您可以这样做:
# Create a test df:
>>> df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df
a b c d e
0 0.675006 0.230464 0.386991 0.422778 0.657711
1 0.250519 0.184570 0.470301 0.811388 0.762004
2 0.363777 0.715686 0.272506 0.124069 0.045023
3 0.657702 0.783069 0.473232 0.592722 0.855030
现在解析html并重新构建:
from pyquery import PyQuery as pq
d = pq(df.to_html())
columns = d('thead tr').eq(0).text().split()
n_rows = len(d('tbody tr'))
values = np.array(d('tbody tr td').text().split(), dtype=float).reshape(n_rows, len(columns))
>>> DataFrame(values, columns=columns)
a b c d e
0 0.675006 0.230464 0.386991 0.422778 0.657711
1 0.250519 0.184570 0.470301 0.811388 0.762004
2 0.363777 0.715686 0.272506 0.124069 0.045023
3 0.657702 0.783069 0.473232 0.592722 0.855030
如果需要,您可以使用eval()
将其扩展为多索引dfs或自动类型检测。pandas 0.12中发布的实用程序我认为不是,但是如果有lxml
的帮助,它应该不会太难……而且,转换为html
也是有损的,由于类型信息丢失,因此您需要自己指定。无论如何,如果df
相对简单(例如,统一的数据类型),转换应该只需要几行代码。pandas有一些类型推断方法试图缓解这个问题,它们做得很好。