代码之家  ›  专栏  ›  技术社区  ›  marc

读取数据帧的数据类型不正确

  •  0
  • marc  · 技术社区  · 6 年前

    我使用pandas数据框读取一个如下的日志文件

    col1 col2 col3
    2 3 string1
    3 4 string2
    5 6 string3
    
    df = pd.read_csv(path-to-log, header=None)
    df.dtypes
    
    0 object
    1 object
    2 object
    

    我希望产量

    0 float64
    1 float64
    2 object
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   jpp    6 年前

    日志文件包含头,因此不需要提供 header=None .另外,您的分隔符是空格,因此您可以使用 delim_whitespace=True .

    注意前两列是作为整数而不是浮点数读取的,因为只有整数存在。下面是一个演示:

    import pandas as pd
    from io import StringIO
    
    mystr = StringIO("""col1 col2 col3
    2 3 string1
    3 4 string2
    5 6 string3""")
    
    df = pd.read_csv(mystr, delim_whitespace=True)
    
    print(df)
    
       col1  col2     col3
    0     2     3  string1
    1     3     4  string2
    2     5     6  string3
    
    print(df.dtypes)
    
    col1     int64
    col2     int64
    col3    object
    dtype: object
    
        2
  •  0
  •   Rohin    6 年前

    不使用header=none

    df = pd.read_csv('test.log', sep=' ')

    输出-

    col1     int64
    col2     int64
    col3    object