首页 > 解决方案 > 有没有办法使用 Python 在 Excel 中执行类似 SQL 的 Select 语句?

问题描述

鉴于此 Excel 表: Excel 文件

假设 SQL Select 语句如下所示:

Select Status from sheet where name = "John Doe" and age = 20

并返回与姓名/年龄匹配的行的状态值 Excel 也可以有超过 1 行。

我还添加了一个从 excel 复制粘贴,但它粘贴了一张图片,我不知道如何分享实际的 excel 内容

标签: pythonexcelpandasxlrd

解决方案


您可以使用DataFrame.query()方法。像下面这样的东西应该可以完成这项工作:

>>> df

           Name  Age  Height       Status
0      John Doe   20     180  Not Married
1  Jhonny Dolly   20     170      Married

>>> df.query('Name == "John Doe" and Age == 20')

       Name  Age  Height       Status
0  John Doe   20     180  Not Married

>>> df.query('Name == "John Doe" and Age == 20')[['Status']]

        Status
0  Not Married

推荐阅读