【问题标题】:Pandas read_html() converts numbers in table to stringPandas read_html() 将表格中的数字转换为字符串
【发布时间】:2015-12-10 16:58:31
【问题描述】:

我有一个要转换为 pandas 数据框的 html 表。我正在使用pandas.read_html(),它可以正常工作,只是它将表格中的数字作为字符串读取。

table = html_table_here
table = '<table border="1" class="dataframe">\n  '+table+'    \n</table>'
df_table = pandas.read_html(table,header=None,index_col=0)
df = pandas.concat(df_table)

并且执行print df["TASK_ID"][0] 返回"3" 而不是3

在转换为 pandas 数据框时,是否有保留 html 表中值的类型?

【问题讨论】:

  • 您必须将这些值显式转换为数字 dtypes df_table = df_table.convert_objects(convert_numeric=True) 因为这里无法猜测 html 值是 str 还是 numeric

标签: python html pandas


【解决方案1】:

您必须将这些字符串显式转换为数字 dtype,因为当它们在 html 中是 str 时,它无法判断 dtype 是什么,因此调用 convert_objects 应该可以工作:

df_table = df_table.convert_objects(convert_numeric=True)

【讨论】:

    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 2017-06-04
    • 2016-09-17
    • 2020-11-20
    • 2019-01-14
    • 2014-01-25
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多