【问题标题】:Difficulty importing .dat file难以导入 .dat 文件
【发布时间】:2016-06-09 18:13:28
【问题描述】:

我在使用 pandas read_table 函数将这个文件读入 python 时遇到了一些困难。 http://www.ssc.wisc.edu/~bhansen/econometrics/invest.dat

这是我的代码:

pd.read_table(f,skiprows=[0], sep="")

产生错误:

TypeError: ord() expected a character, but string of length 0 found

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    不知道read_table,但是可以直接读取这个文件,如下:

    import pandas as pd    
    
    with open('/tmp/invest.dat','r') as f:
        next(f) # skip first row
        df = pd.DataFrame(l.rstrip().split() for l in f)
    
    print(df)
    

    打印:

                  0            1             2            3
    0     17.749000   0.66007000    0.15122000   0.33150000
    1     3.9480000   0.52889000    0.11523000   0.56233000
    2     14.810000    3.7480300    0.57099000   0.12111000
    ...
    ...
    

    同样可以得到如下:

    df = pd.read_csv('/tmp/invest.dat', sep='\s+', header=None, skiprows=1)
    

    【讨论】:

    • 只是认为使用内置函数这样做可能更有效。你知道用内置函数来做吗?
    • 你可以简单地使用skiprows=0
    • 非常感谢。我认为诀窍是在 sep 参数中使用正则表达式。因为当我使用“\s+”时,即使使用 read_table,它也可以工作。
    • 很高兴听到它现在好了:-)
    • 也感谢您的\s+。导入时空格数不一致不能使用简单的' '空格。
    猜你喜欢
    • 2015-11-27
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    相关资源
    最近更新 更多