首页 > 解决方案 > 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)

This gives me an output of:

['hi' 'See you']

The end purpose is to basically iterate through all columns from 2nd row onwards to look for keyword match (which is why I put: if index>0) and if it finds a match, then to output by default the first item of that column (in this case "Greetings to you too" which is df3.iloc[0,0] in this scenario.

Hence I need help to add additional line of code, so that the result output after running the code will look like this:

"Greetings to you too"

Could someone help please.

标签: pythonpandasfor-loopiteration

解决方案


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

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

推荐阅读