如何在Python中读取大型文本文件?
我正在使用Enthound Canopy(一组不同的Python库包,例如NumPy、Pandas等)进行数据分析。我试图读取一个文本文件,并从中创建一个数据帧。文本文件有1180598行和18列。所有列中都有数字。我编写了以下用于读取和命名数据列的代码:如何在Python中读取大型文本文件?,python,pandas,enthought,Python,Pandas,Enthought,我正在使用Enthound 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
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)
从熊猫导入数据帧,读取
将matplotlib.pyplot作为plt导入
作为pd进口熊猫
打印“熊猫版”+pd.\u版__
熊猫版本0.12.0
location=r'C:\UMAIR\Directed Studies\US-101 Data\Main Data\US-101-Main-Data\vehicle tract Data\0750am-0805am\tra.txt'
df=读取值(位置,名称=[‘车辆ID’、‘帧ID’、‘总帧’、‘全局时间’、‘局部X’、‘局部Y’、‘全局X’、‘车辆长度’、‘车辆宽度’、‘车辆等级’、‘车辆速度’、‘车辆加速度’、‘车道识别’、‘前车’、‘后车’、‘间距’、‘车头时距’)
df
出[41]:
INT64索引:1180598个条目,0到1180597
数据列(共18列):
车辆ID 1180598非空值
帧ID 0非空值
总帧数0个非空值
全局时间0非空值
本地X 0非空值
局部Y 0非空值
全局X 0非空值
全局Y 0非空值
车辆长度0非空值
车辆宽度0非空值
车辆类别0非空值
车辆速度0非空值
车辆加速度0非零值
车道标识0非空值
前车0非空值
跟车0非空值
间隔0个非空值
间隔0非空值
数据类型:float64(17),object(1)
正如您从[41]中看到的,该文件被读取为只有一列。我应该如何让Python知道我的文件有18列,以便按原样读取?这将正确导入数据集:
df = pd.read_csv(location, names=names, header=None, delim_whitespace=True)
请张贴您的文件样本;您指定了分隔符了吗?