簡體   English   中英

使用 for 循環遍歷 pandas 數據幀時,go 返回上一行

[英]go back to previous row when iterating through a pandas data frame using for loop

我有一個類似於下面的 dataframe:

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

我正在嘗試遍歷此數據框以向用戶顯示“文本”列的字符串,以便他們可以命名這些字符串。 我還想為用戶提供返回到以前顯示的字符串的機會,以防他們改變主意並需要重命名以前的字符串。 我怎樣才能實現這個目標? 我正在嘗試以下代碼:

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

如果您想 go 回到上一行,那么您應該使用while -loop 並手動更改index += 1index -= 1並獲取text = data['text'][index]row = data.iloc[index]

但所有這些只有在索引使用連續數字時才有效。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM