在Python中读取ASCII文件(numpy数组?) [英] Reading ASCII file in Python (numpy-array?)

查看:1716
本文介绍了在Python中读取ASCII文件(numpy数组?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Python读取ASCII文件时遇到问题.这是文件的示例: http://pastebin.com/CTwwPPKA

I have a problem reading ASCII file in Python. Here's an example of the file: http://pastebin.com/CTwwPPKA

我尝试使用numpy的genfromtxt:

I tried using numpy's genfromtxt:

data = np.genfromtxt("example.txt")

但是这种方式我无法正确读取日期和时间,因为它们应该是datetime对象. 另一方面,loadtxt只能读取浮点值,这也是不可接受的.

But this way I cannot read dates and times properly since they should be datetime objects. On the other hand, loadtxt can only read float values, which is also not acceptable.

您能建议我一种正确读取此类文件的方法吗?

Could you please suggest me a way to properly read that kind of file?

推荐答案

您必须在此处使用dtype选项.

you have to use dtype option here.

x = np.genfromtxt("example.txt", dtype=None)
print(x[0])

您将得到

('DATA', 34967565, '2011-08-04', '19:00:00:081', 0.0272448, -0.17718500000000001, 4.2143899999999999, 524.57600000000002, 17.485499999999998, 101.07599999999999, 0.45927400000000002, 0.19031300000000001, 0.100296, 0.97492599999999996, 1.94354, 100.73399999999999, 12.538600000000001, 10.3786, 44318.5, 39605.5, 39234.5, 40298.0, 68)

这里的窍门是必须将dtype指定为None,以便numpy可以自动识别字符串和数字,而默认的dtype是浮点型.

The trick here is that you have to specify dtype to None so that numpy can automatically recognize strings and numbers, while the default dtype is float.

然后,您可以使用 datetime.strptime 来转换日期时间对象的字符串.

Then you can use datetime.strptime to convert the strings to datetime objects accordingly.

这篇关于在Python中读取ASCII文件(numpy数组?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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