samedi 18 avril 2015

Use For loop in an If statement - python

Problem


I have a table made of 380 rows and 20 columns. I want to remove rows from this table following a certain condition.


To clarify things, let's say I have the list:



names = ['John', 'Amy', 'Daniel']


I want to remove the data of all the people whose name is found in the list names.


Example, let's say my data looks something like this:



John 82 3.12 boy
Katy 12 1.12 girl
Amy 42 2.45 girl
Robert 32 1.56 boy
Daniel 47 2.10 boy


I want to remove the data of John, Amy, and Daniel. So the output should be:



Katy 12 1.12 girl
Robert 32 1.56 boy


Attempt to solve it



import csv
import numpy as np

# loading data
data = np.genfromtxt('file.txt', dtype = None)

csvfile = "home/paula/Desktop/test.txt"
with open(csvfile, 'w') as output:
writer = csv.writer(output, delimiter = '\t')

for row in range(len(data)):
if data[row][0] == (i for i in names):
print 'removing the data of', i, '...'
else:
writer.writerow([data[row][0], data[row][1],
data[row][2], data[row][3]])


My code is working, however the data was not deleted from my original data. When I open the new test.txt file, I can see that the data was not deleted.


I am certain that the bug is in if data[row][0] == (i for i in names): How can I fix this?


Aucun commentaire:

Enregistrer un commentaire