我有一个.txt文件,其中包含一个表格,例如:
对象大小数量
1 2 3
2 10 3
3 4 1
4 5 2
5 12 1
6 6 2
7 17 4
8 19 2
9 9 3
10 14 2
我已使用以下代码将此表带到Python:
import numpy as np
X = np.loadtxt('table1.txt', skiprows=1)
print(X)
现在,我想删除“大小”小于10的所有行。然后,我想看到省略了这些行的“新”表。如何使用Python做到这一点?
谢谢,Q
答案 0 :(得分:0)
除了@Mark Meyer的评论/答案,这是我在Python中的方法。
with open('sample.txt','r') as f:
c = f.readlines()
c = [ x.strip('\n').split() for x in c[2:] if x.strip('\n') !='']
# Assign elements to a list [['1', '2', '3'], ['2', '10', '3'] ...
min_number = 10 # ciriteria
c = [c[index] for index, value in enumerate(c) if int(value[1]) > min_number ]
# Keep elements that respect the criteria [['5', '12', '1'] ...
# If you want to keep 10 too, modify list comprehension to >=
# Write output to same file
with open('sample.txt','w') as f:
for iter, each_line in enumerate(c): # resetting the row number to 1,2, ..
f.write('{}\t{}\t{}\n'.format( iter+1,each_line[1],each_line[2] ) )