user144153 user144153 - 5 months ago 18
Python Question

Loop through table and remove rows without using object index

I've been teaching myself python, and currently I'm trying to loop through an astropy table and replace any rows that have a certain value in the second column. I can write a script that accomplishes this, but not without using a dummy index to keep track of what row I'm on.

for value in my_list:
k=0
for row in data_table:
if value == row[1]:
data_table.remove_row(k)
data_table.add_row([replacement_row])
k+=1
else:
k+=1


What I'm wondering is whether or not there is there a row.index() attribute or something similar that would allow me to write

for value in my_list:
for row in data_table:
if value == row[1]:
data_table.remove_row(row.index())
data_table.add_row([replacement_row])


The original code I have written doesn't seem like the most pythonic way.

Answer

Someone pointed out to me that this can be done using enumerate()

for value in my_list:
    for row in enumerate(data_table): 
        if value == row[1][1]: 
            data_table.remove_row(row[0])
            data_table.add_row([replacement_row])
Comments