python - 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 循环?!
解决方案
将您的功能替换为以下内容:
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
推荐阅读
- node.js - 通过 lambda nodejs(流式传输)从 AWS RDS(SQL Server)到 S3 存储桶
- java - 无法提取从 Java 创建的 zip 文件
- javascript - JavaScript+Html:将 JavaScript 变量插入到按钮的 onclick 函数参数中
- javascript - 在 ReactJS 中使用 Cesium 对引脚进行聚类
- python - 如何将枚举成员添加到 openpyxl 工作表
- visual-studio - 每次运行 IIS express 错误 500.0
- azure-active-directory - 从所有组中检索所有用户?
- sql - SAP HANA - 当旧表有插入时触发插入新表
- c# - ASP.NET UpdateProgress 不显示
- python - 简单的 python 循环,一旦读取一个新值就会创建一个新行