python - 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.
解决方案
我终于得到了答案,代码只需要调整一下:
for index, row in df3.iterrows():
if index>0:
if sentence.lower() in df3.iloc[index,:].values:
print((df3.iloc[:index]).iloc[0,0])
推荐阅读
- curl - 在 curl 中,如何强制标头内容类型为 application/json?
- java - 如何仅为特定用户检索firebase数据库?
- javascript - 我无法使用 java 脚本在 firebase 云数据库中添加和编辑数据。我可以选择数据但无法添加数据
- xampp - 本地主机上奇怪的 HTML 加载行为 - Xampp
- javascript - 强制不受支持的浏览器忽略 VIBRATION API 方法
- android - WebView 页面不会在 Xamarin 表单中加载 url
- amazon-web-services - 如何使用 AppSync 解决父子关系
- reactjs - 从子组件调用父函数不起作用
- crystal-lang - 在初始化程序中分配的实例变量被错误地推断为 nilable
- selenium - 如何修复 org.openqa.selenium.WebDriverException:更新 selenium 库后