在Pandas Dataframe中打印下一行

时间:2016-12-23 16:29:13

标签: python pandas

我有一个由聊天机器人数据组成的 pandas dataframe ,我想打印用户的输入以响应特定的聊天机器人消息,例如:

(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列的数据帧,我想打印用户输入的具体问题“你好,你有什么爱好?”仅

我尝试了下面的代码来打印Bot的问题,但是我无法找到一种方法来获得用户对该特定问题的回答。

for i in Chat_Column:
    if i =="Bot: Hi, What are your hobbies?":        
        print (i);

基本上我在这种情况下想要的输出是:

User1: Cricket, FootBall
User3: Tennis, Baseball

3 个答案:

答案 0 :(得分:2)

您应首先获取与DataFrame的def get_score(self, cr, uid, ids, context={}, arg=None,obj=None): result = {} for f in self.browse(cr, uid,ids): net_score = float(f.earn_score.f.availed_score) result[f.id] = net_score return result 'net_score': fields.function(get_score, method=True, string='Net Score',type='float'), 函数匹配问题的行的索引。要与您的问题进行部分匹配,请使用index

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 包含与您的查询匹配的索引列表。在最后一行中,打印与这些索引相对应的下一行的值。

答案 1 :(得分:0)

使用@CentAu的数据框声明

import pandas as pd

Chat_Column = 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"]
               })

for ndx, row in Chat_Column.iterrows():
    if "Bot: Hi, What are your hobbies?" in row["data"]:
        print(Chat_Column.iloc[ndx+1]["data"])

答案 2 :(得分:0)

d = {'a':['Question1','Answer1','Question2','Answer2','Question3','Answer3']}
df = pd.DataFrame(d)
print df['a'].shift(-1)[df['a'] == 'Question2'].values[0]

但我建议将数据框放入两列(Quesiton和Answer)。

注意事项 - 使用pandas本机索引比在每次迭代中迭代字符串列表和测试if语句要快得多。也就是说,它可能无关紧要,如果它只有几百/千行,但如果DataFrame的大小增加则可能很明显。