我有以下代码,运行超过一百万行。但这需要很多时间。有更好的方法来阅读这些文件吗?当前代码如下所示:
for line in lines:
line = line.strip() #Strips extra characters from lines
columns = line.split() #Splits lines into individual 'strings'
x = columns[0] #Reads in x position
x = float(x) #Converts the strings to float
y = columns[1] #Reads in y
y = float(y) #Converts the strings to float
z = columns[2] #Reads in z
z = float(z) #Converts the strings to float
文件数据如下所示:
347.528218024 354.824474847 223.554247185 -47.3141937738 -18.7595743981
317.843928028 652.710791858 795.452586986 -177.876355361 7.77755408015
789.419369714 557.566066378 338.090799912 -238.803813301 -209.784710166
449.259334688 639.283337249 304.600907059 26.9716202117 -167.461497735
739.302109761 532.139588049 635.08307865 -24.5716064556 -91.5271790951
我想从不同的列中提取每个数字。列中的每个元素都是同一个变量。我怎么做?例如,我想要一个列表,l,比如存储第一列的浮点数。
答案 0 :(得分:4)
知道您计划对数据做什么会很有帮助,但您可以尝试:
data = [map(float, line.split()) for line in lines]
这将为您提供包含数据的列表列表。
答案 1 :(得分:1)
Pandas是为此而建的(在许多其他事情中)!
它使用numpy,它在引擎盖下使用C并且非常快。 (实际上,根据你对数据的处理方式,你可能想直接使用numpy而不是pandas。但是,我只会在你尝试过大熊猫之后这样做; numpy是较低级别的,大熊猫会让你的生活更容易。)
以下是您可以阅读数据的方式:
import pandas as pd
with open('testfile', 'r') as f:
d = pd.read_csv(f, delim_whitespace=True, header=None,
names=['delete me','col1','col2','col3','col4','col5'])
d = d.drop('delete me',1) # the first column is all spaces and gets interpreted
# as an empty column, so delete it
print d
输出:
col1 col2 col3 col4 col5
0 347.528218 354.824475 223.554247 -47.314194 -18.759574
1 317.843928 652.710792 795.452587 -177.876355 7.777554
2 789.419370 557.566066 338.090800 -238.803813 -209.784710
3 449.259335 639.283337 304.600907 26.971620 -167.461498
4 739.302110 532.139588 635.083079 -24.571606 -91.527179
在这种情况下,结果d
是一个称为dataframe的强大数据结构,它为您提供了很多用于快速操作数据的选项。
作为一个简单的例子,这会添加两个第一列并获得结果的平均值:
(d['col1'] + d['col2']).mean() # 1075.97544372
Pandas也很好地处理丢失的数据;如果数据文件中存在缺失/错误值,那么当pandas读取它们时,它们将根据需要用NaN
或None
替换它们。
无论如何,为了快速,简便的数据分析,我强烈推荐这个库。