【问题标题】:Python DataFrame loop and slice issuePython DataFrame循环和切片问题
【发布时间】:2018-10-13 10:38:43
【问题描述】:
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循环?!

【问题讨论】:

    标签: python pandas loops dataframe slice


    【解决方案1】:

    将您的函数替换为以下内容:

    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
    

    【讨论】:

    • 这段代码有问题,它只适用于“再见”。但是,当我输入“再见”时,它给了我“也向你问好”。应该做的是,如果我输入“hi”、“hello”、“hey”、“greetings”、“sup”、“what's up”、“yo”等任何内容,来给我“问候你”。以及“再见”、“再见”、“稍后”的任何输入,给我“再见”的输出。您建议的代码没有这样做:(
    • @Muke888 操作,对不起。没注意到。我已经改变了上面的答案。其实不用iterrows把事情复杂化。
    • 感谢 R.yan!现在几乎完成了,我唯一遇到的问题是它在不应该的时候复制了输出!我更新了帖子,你能帮忙吗?提前致谢!
    • 重复输出是由于您正在循环单词列表。如果找到该单词,请添加 break 以停止循环。
    • @ Muke888 我上面的答案已更新以修复您的重复输出。
    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 2020-10-05
    • 2013-09-26
    • 2021-05-03
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多