微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Python中读取大文本文件?

我正在使用Enthought Canopy(一组许多不同的Python库包,例如NumPy,Pandas等)进行数据分析.我正在尝试读取文本文件并从中创建数据框.该文本文件有1180598行和18列.所有列都包含数字.我编写了以下用于读取和命名数据列的代码

from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt

import pandas as pd

print 'Pandas Version ' + pd.__version__
Pandas Version 0.12.0

location=r'C:\UMAIR\Directed Studies\US-101 Data\Main Data\US-101-Main-Data\vehicle-trajectory-data\0750am-0805am\tra.txt'

df=read_csv(location, names=['Vehicle ID','Frame ID','Total Frames','Global Time','Local X','Local Y','Global X','Global Y','Vehicle Length','Vehicle Width','Vehicle Class','Vehicle VeLocity','Vehicle acceleration','Lane Identification','Preceding Vehicle','Following Vehicle','Spacing','Headway'])

df
Out[41]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1180598 entries, 0 to 1180597
Data columns (total 18 columns):
Vehicle ID              1180598  non-null values
Frame ID                0  non-null values
Total Frames            0  non-null values
Global Time             0  non-null values
Local X                 0  non-null values
Local Y                 0  non-null values
Global X                0  non-null values
Global Y                0  non-null values
Vehicle Length          0  non-null values
Vehicle Width           0  non-null values
Vehicle Class           0  non-null values
Vehicle VeLocity        0  non-null values
Vehicle acceleration    0  non-null values
Lane Identification     0  non-null values
Preceding Vehicle       0  non-null values
Following Vehicle       0  non-null values
Spacing                 0  non-null values
Headway                 0  non-null values
dtypes: float64(17), object(1) 

从Out [41]可以看出,文件读取只有1列.我应该怎么做才能让Python知道我的文件有18列,以便按照它的方式读取?

解决方法:

这将正确导入您的数据集:

df = pd.read_csv(location, names=names, header=None, delim_whitespace=True)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐