首页 > 解决方案 > Python DataFrame循环和切片问题

问题描述

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 循环?!

标签: pythonpandasloopsdataframeslice

解决方案


将您的功能替换为以下内容:

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

推荐阅读