如何在 Pandas 中读取固定宽度格式的文本文件? [英] How do I read a fixed width format text file in pandas?

查看:92
本文介绍了如何在 Pandas 中读取固定宽度格式的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触了熊猫,正在研究如何读取文件.该文件来自 WRDS 数据库,是可追溯到 1960 年代的 SP500 成分列表.我检查了文件,无论我如何使用 read_csv 导入它,我仍然无法正确显示数据.

I just got my hands on pandas and am figuring out how I can read a file. The file is from the WRDS database and is the SP500 constituents list all the way back to the 1960s. I checked the file and no matter what I do to import it using read_csv, I still can't display the data correctly.

df = read_csv('sp500-sb.txt')

df

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1231 entries, 0 to 1230
Data columns: gvkeyx      from      thru     conm
                                        gvkey      co_conm
...(the column names)
dtypes: object(1)

上面的输出块是什么意思?任何事情都会有所帮助.

What does the above chunk of output mean? Anything would be helpful.

推荐答案

Wes 在一封电子邮件中回复了我.干杯.

Wes answered me in an email. Cheers.

这是一个固定宽度格式的文件(不以逗号或制表符分隔,如通常).我意识到熊猫没有固定宽度的阅读器R 确实如此,尽管可以很容易地塑造它.我会看看我能做什么做.同时,如果您可以以另一种格式导出数据(例如csv--真正以逗号分隔)您将能够使用 read_csv 读取它.一世怀疑使用一些 unix 魔法可以将 FWF 文件转换为 CSV文件.

This is a fixed-width-format file (not delimited by commas or tabs as usual). I realize that pandas does not have a fixed-width reader like R does, though one can be fashioned very easily. I'll see what I can do. In the meantime if you can export the data in another format (like csv--truly comma separated) you'll be able to read it with read_csv. I suspect with some unix magic you can transform a FWF file into a CSV file.

我建议您关注 github 上的问题,因为您的电子邮件即将发送从我的收件箱中消失:)

I recommend following the issue on github as your e-mail is about to disappear from my inbox :)

https://github.com/pydata/pandas/issues/920

最好,韦斯

这篇关于如何在 Pandas 中读取固定宽度格式的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆