![](/img/trans.png)
[英]Save memory in Python. How to iterate over the lines and save them efficiently with a 2million line file?
[英]how to select lines with condition and save them in a file
我正在尝试编写一个程序来打开一个仅在行和列中包含数字的文本文件,以将其保存在新文件中。 我选择列的部分有效,而行的部分无效。 我必须选择条件x> 10e13的行(其中x是特定列中的值)。 这是我编写的代码:
import numpy as np
matrix = np.loadtxt('file.dat')
#select columns:
column_indecies = [0]
selected_columns = matrix[:,column_indecies]
x=10E13
#select lines:
for line in matrix:
if float(line) > x:
selected_lines = line
selected_matrix = matrix[selected_lines,selected_columns]
# output:
np.savetxt('new_file.dat', selected_matrix, fmt='%1.4f')
这是终端上的输出错误:
selected_matrix = matrix[selected_lines]
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
我是初学者,有人可以帮助我吗? 我是Mac用户,正在使用python 2.7。 这是我的输入数据的一小部分样本:
185100000000000.0000
121300000000000.0000
257800000000000.0000
43980000000000.0000
不要使用for循环。 代替:
column = matrix[:,0]
x = 10E13
selected = column > x # this is a bool array
selected_matrix = column[selected]
参考: https : //docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.