繁体   English   中英

Python Pandas Dataframe循环迭代

[英]Python Pandas Dataframe loop iteration

import pandas as pd
import re

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)


sentence = 'hi'
for index, row in df3.iterrows():
   if index>0:
       if sentence.lower() in df3.iloc[index,:].values:
           print(df3.iloc[index].values)

这给了我一个输出:

['hi' 'See you']

最终目的是基本上从第二行开始遍历所有列以查找关键字匹配项(这就是我提出的原因:如果index> 0)并且找到匹配项,则默认情况下输出该列的第一项(在这种情况下,“ greetings also you'sgreeting”也就是df3.iloc [0,0]。

因此,我需要帮助来添加其他代码行,以便运行代码后的结果输出如下所示:

"Greetings to you too"

有人可以帮忙吗。

我终于得到了答案,代码只需要进行一些调整:

for index, row in df3.iterrows():
            if index>0:
                if sentence.lower() in df3.iloc[index,:].values:
                    print((df3.iloc[:index]).iloc[0,0])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM