Home > Software design >  go back to previous row when iterating through a pandas data frame using for loop
go back to previous row when iterating through a pandas data frame using for loop

Time:09-27

I have a dataframe similar to the below:

data = {'part': ['c', 'c', 'c', 'p', 'p', 
'p', 'p', 'p'], 'index': [0,1,2,3,4,5,6,7], 'text': 
['a','b','c', 'd', 'e', 'f', 'g', 'h'], 'class': [[1,0,0], 
[0,1,0], [1,1,0], None , None , None  , None , None]}


data = pd.DataFrame(data)

data

I am trying to iterate through this data frame to display the strings of the column "text" to users so that they can name these strings. I also want to provide users the chance to return to previously presented strings in case they change their mind and need to rename previous strings. How can I achieve this goal? I am trying the below code:

for n, c in enumerate(data['text']):
    a = input(f"Enter labels for the text or enter 2 to go back to 
        previous: \n\n{c}\n\n: ")
    if a == '2':
        idx = n - 1
        c = c[idx]
    



IndexError                                Traceback (most recent 
call last)
<ipython-input-59-ca3c4aa6f370> in <module>
      3   if a == '2':
      4     idx = n - 1
----> 5     c = c[idx]
      6 
      7 

IndexError: string index out of range

CodePudding user response:

If you want to go back to previous row then you should use while-loop and manually change index = 1 or index -= 1 and get text = data['text'][index] or row = data.loc[index]

But all this will work only if indexes use consecutive numbers.

import pandas as pd

data = {
    'part': ['c', 'c', 'c', 'p', 'p', 'p', 'p', 'p'],
    'index': [0, 1, 2, 3, 4, 5, 6, 7],
    'text': ['a','b','c', 'd', 'e', 'f', 'g', 'h'],
    'class': [[1,0,0], [0,1,0], [1,1,0], None , None , None  , None , None]
}

data = pd.DataFrame(data)
data['label'] = ''
print(data)

index = 0

while index < len(data):
    row = data.loc[index]
        
    print("Enter labels for the text or enter 2 to go back to previous:")
    print()
    print('index:', index)
    print('text :', row['text'])
    print('label:', row['label'])
    print()
    
    label = input(": ")
    
    if label == '2':
        index -= 1  # go to previous
        if index < 0:
            print('There is no previous row')    
            index = 0
    else:
        #row['label'] = label
        data.loc[index, 'label'] = label
        index  = 1  # go to next
    
print(data)
  • Related