在 pandas 数据框中打印下一行 [英] Print Next Line in Pandas Dataframe
问题描述
我有一个由聊天机器人数据组成的 pandas数据框,我想打印用户的输入以响应特定的聊天机器人消息,例如:
I have a pandas dataframe consisting of chat bot data and I want to print the User's input in response to a specific chat bot message eg:
(Row 1) Bot: Hi, What are your hobbies?
(Row 2) User1: Cricket, FootBall
(Row 3) Bot: Hi, What is your name?
(Row 4) User2: Alexa
(Row 5) Bot: Hi, What are your hobbies?
(Row 6) User3: Tennis, Baseball
因此,基本上,我有一个如上所述的6行1列的数据框,我想将用户输入的内容打印到特定的问题您的爱好是什么?"
So basically I have a dataframe with 6 rows and 1 column as above and I want to print the user's input to the specific question "Hi, What are your hobbies?" only.
我尝试了下面的代码来打印Bot的问题,但是我无法找到一种方法来获取用户对特定问题的答案.
I tried the following code which prints the Bot's question but I am unable to find a way to get the User's answer to that specific question.
for i in Chat_Column:
if i =="Bot: Hi, What are your hobbies?":
print (i);
在这种情况下,我想要的输出基本上是:
Basically the output I want in this case is:
User1: Cricket, FootBall
User3: Tennis, Baseball
推荐答案
您首先应该通过DataFrame的index
函数获取与问题匹配的行的索引.要部分匹配您的问题,请使用str.contains
.
You should first get the index of the row that matches the question by index
function of DataFrame. To get partial match to your question, use str.contains
.
df = pd.DataFrame({'data':
["(Row 1) Bot: Hi, What are your hobbies?",
"(Row 2) User1: Cricket, FootBall",
"(Row 3) Bot: Hi, What is your name?",
"(Row 4) User2: Alexa",
"(Row 5) Bot: Hi, What are your hobbies?",
"(Row 6) User3: Tennis, Baseball"]
})
idx = df[df['data'].str.contains("Hi, What are your hobbies?")].index.tolist()
for i in idx:
if i < len(df) - 1:
print(df.iloc[i + 1].values[0])
输出:
(Row 2) User1: Cricket, FootBall
(Row 6) User3: Tennis, Baseball
因此,在上面的代码中,idx
包含与您的查询匹配的索引列表.在最后一行中,打印与这些索引相对应的下一行的值.
So, in the above code, idx
holds a list of indexes that match your query. In the last line, you print the values of the next row corresponding those indices.
这篇关于在 pandas 数据框中打印下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!