Skip to main content
 首页 » 编程设计

Python DataFrame 循环和切片问题

2024年09月07日7thcjp

import random 
import re 
import pandas as pd 
df1 = pd.DataFrame({"Greetings": ["Greetings to you too", "hi", "hello", "hey", "greetings", "sup", "what's up", "yo"]}) 
df2 = pd.DataFrame({"Farewell": ["GoodBye", "see you", "bye", "laters"]}) 
 
frames = [df1, df2] 
df3=pd.concat(frames, axis=1, join='outer', copy=True) 
def check_for_greet(): 
 while True: 
    try: 
        sentence = input("Start chatting:  ") 
        wordList = re.sub("[^\w]", " ",  sentence).split() 
        if sentence == "$$$": 
                return "END" 
 
        for word in wordList: 
            for col in df3.columns: 
                if word.lower() in df3[col].values: 
                    print (df3[col][0]) 
                    break 

上面的内容现在在列之间完美运行(谢谢@R.yan),但是唯一的问题是当我输入“hi hi”时,它会打印两次:

Start chatting:  hi hi 
Greetings to you too 
Greetings to you too 

为什么要这样做,我正在打破 for 循环并继续返回到 while 循环?!

请您参考如下方法:

用以下内容替换您的函数:

def check_for_greet(): 
 while True: 
    try: 
        sentence = input("Start chatting:  ") 
        wordList = re.sub("[^\w]", " ",  sentence).split() 
        if sentence == "$$$": 
                return "END" 
 
        for col in df3.columns: 
            if sentence.lower() in df3[col].values: 
                print df3[col][0] 
        continue 

输出:

Start chatting:  hi 
Greetings to you too 
Start chatting:  bye 
GoodBye 

重复输出的答案

word_found = False 
for word in wordList:           
    for col in df3.columns: 
        if word.lower() in df3[col].values: 
            print (df3[col][0]) 
            word_found = True 
    if word_found: 
        break