导入.dat fi困难

2024-06-16 10:02:41 发布

您现在位置:Python中文网/ 问答频道 /正文

不知怎么的,我很难用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

Tags: 文件函数代码httppandasreadwwwtable
1条回答
网友
1楼 · 发布于 2024-06-16 10:02:41

不知道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)

相关问题 更多 >