【问题标题】:How to iterate through columns and rows in excel with Python?如何使用 Python 遍历 excel 中的列和行?
【发布时间】:2021-02-25 21:21:45
【问题描述】:

我是一个自学成才的初学者“”“编码器”“”。对于我正在编写的更大的脚本,我需要编写一个函数来检查用户的输入是否存在于列(例如)A 中的 excel 文件中,如果存在,则返回列中同一行的值(说)B。

Screenshot of a sample excel file

在上图中,我会检查输入是否是 Seth,我会返回 500,如果是 John,我会返回 800,等等。

我发现 xlrd 和 pandas 文档非常混乱。我在 ifs 和 for 循环之间被阻塞了。这是我想到的伪代码和 Python 的混合体。

listA = column A
listB = column B
for i in listA:
    if input in listA:
        return i.listB

我想象过类似的事情,但我无法将其付诸实践。提前非常感谢您!

【问题讨论】:

  • 您在读取 ​​excel 文件时遇到问题吗?在 Pandas 中解析 DataFrame?还有什么?
  • 我的第一个麻烦是:如何检查输入是否在excel的列中。这包括读取特定列和(猜测)遍历其所有元素。我认为克服它会推动我走到最后。

标签: python python-3.x pandas openpyxl xlrd


【解决方案1】:

最好的方法是查找字典,它存储 A 列中的所有值以及 B 列中的相应值,因此您可以在需要给定键的值时快速查找它们。 至少这对于小文件来说是个好主意。如果查找占用太多内存,您将不得不恢复扫描 excel 文件。

要使用字典,只需加载 excel 表并将感兴趣的两列整理到字典中。然后,您可以使用 try-except 块来检索值或输出错误消息。

import pandas

data = pandas.read_excel("example.xlsx")
lookup = dict(zip(data["Names"],data["Values"]))

n = input("\nEnter the name: ")

try:
    print("The value is: "+str(lookup[n]))
except:
    print("There is no such name in the file")

我使用了一个类似于你的 excel 文件并得到了答案:

Enter the name: John
The value is: 800

Enter the name: Peter
The value is: 354

Enter the name: William
The value is: 132

Enter the name: Fritz
There is no such name in the file

Enter the name: Santa
There is no such name in the file

【讨论】:

  • 我认为这很棒。还有一个问题:小文件有多大?我可以将它用于(比如说)每列 100 个元素吗?我的实际文件是每列大约 40 个元素。
  • 在这方面的“小文件”是指小于 100MB 的文件。我目前使用这种技术对包含 60'000 到 200'000 个条目的 CSV 进行排序。所以,100 行就很好了。
  • 永远不要使用不合格的except 子句。
猜你喜欢
  • 2017-06-02
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多