【问题标题】:Python Pandas Dataframe loop iterationPython Pandas Dataframe 循环迭代
【发布时间】:2018-10-13 06:17:41
【问题描述】:
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']

最终目的是从第二行开始遍历所有列以查找关键字匹配(这就是我输入的原因:if index>0),如果找到匹配项,则默认输出第一项该列(在本例中为“向您致以问候”,在本例中为 df3.iloc[0,0]。

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

"Greetings to you too"

有人可以帮忙吗。

【问题讨论】:

  • 你的描述很混乱。请举例说明您期望的结果。
  • 我编辑了这篇文章,希望它能让它更容易理解。我只需要最后的输出来显示“向你问好”。
  • 我不了解你
  • 将最后一个打印语句从print(df3.iloc[index].values) 更改为print(df3.iloc[:index].values),然后将打印[['Greetings to you too' 'GoodBye']]。问题是 df3.iloc 第一个索引在行上运行,而第二个索引在列上运行。
  • @prabhakar,该建议输出该索引处所有行的值,我需要的只是输出“向你问候”。

标签: python pandas for-loop iteration


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2021-02-24
    • 2016-06-07
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2020-05-21
    • 2020-01-03
    • 2018-06-06
    相关资源
    最近更新 更多