选择另一列

时间:2017-09-04 15:10:39

标签: python numpy

1   0   0       0.579322 
2   0   0       0.579306 
3   0   0       0.279274
4   5   0       0.579224
5   3   0       0.579157 
3   0   0       0.47907
7   0   1       0.378963
8   9   0       0.578833

我是python的初学者并努力做到这一点。我有四个如上所述的列,我需要保存1,2,3列,其值大于0.4且小于0.5的列。这可以通过numpy完成吗? 这是我试过的代码。

import csv

csv_out = csv.writer(open('data_new.csv', 'w'), delimiter=',')

f = open('coordiantes.txt',"w+")
for line in f:
 vals = line.split('\t')
  for vals ([3]>=0.4 & vals[3]<=0.5):
   print vals[0],vals[1],vals[2]
csv_out.writerow(vals[0], vals[1], vals[2],vals[3])
f.close()

2 个答案:

答案 0 :(得分:0)

可以使用一些内置的numpy函数来完成

vals = #your array

#do a Boolean index of your array where the fourth column meets your criteria
vals = vals[np.where((vals[:,3] <=0.5)&(vals[:,3]>0.4))]

#use numpy to slice off last column and  to save the file
np.savetxt('coordiantes.txt',vals[:,:3],delimiter=',')

答案 1 :(得分:0)

您可以执行以下操作:

import numpy as np

data = np.loadtxt('coordinates.txt')
idx = np.where((data[:,3] <= 0.5) & (data[:,3] > 0.4))[0] # save where col 4's data is in (0.4,0.5]
selected_data = data[idx,:3] # get the 1st three cols for the rows of interest
np.savetxt('data_new.csv', selected_data, delimiter=',')