【问题标题】:Is there a way to do a Select statement like SQL in Excel using Python?有没有办法使用 Python 在 Excel 中执行类似 SQL 的 Select 语句?
【发布时间】:2021-08-22 08:56:52
【问题描述】:

鉴于此 Excel 表: Excel File

假设 SQL Select 语句如下所示:

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

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

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

【问题讨论】:

    标签: python excel pandas xlrd


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 这看起来很奇怪,我已经尝试过,但我得到了一个奇怪的响应,或者我如何访问查询方法的返回?如果我打印print(df.query('Name == "John doe" and Age == 20')) 它显示:Empty DataFrame Columns: [Name, Age, Height, Status] Index: [] 而且 excel 文件不为空,我不得不使用engine='openpyxl' 打开 excel 文件,给了我 xlsx 扩展名的错误 bcs
    • 我用小写字母打错了 Doe。尝试按照上面的示例进行更改(区分大小写)
    • 确实有效,谢谢!还有一件事,查询的结果可以转换成字典吗?假设:`{Name': 'John Doe', 'Age': 20, 'Height': 180, 'Status': 'Not Married'} ?
    • 是的。试试这个:df.query('Name == "John Doe" and Age == 20').to_dict(orient='records')
    • 你太客气了哈哈,谢谢!确实有效!
    【解决方案2】:

    首先,加载你的excel文件:

    df = pd.read_excel("myfile.xlsx")
    

    现在你有了一个数据框:

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

    你可以提出要求:

    >>> df.loc[(df["Name"] == "John Doe") & (df["Age"] == 20), "Status"]
    0    Not Married
    Name: Status, dtype: object
    

    以 SQL 方式:

    name = "John Doe"
    age = 20
    print(df.query('Name == @name and Age == @age')["Status"])
    

    【讨论】:

      【解决方案3】:

      如果您想使用纯 SQL 请求来查询您的 Excel 文件,您首先需要将其转换为数据库。最简单的解决方案是sqlite,因为它是 Python 标准库的一部分,不需要设置 DBMS,与pandas 结合使用。你可以在this answer找到一个例子。

      import pandas as pd
      import sqlite3
      
      db = sqlite3.connect(':memory:')
      dfs = pd.read_excel('somefile.xlsx', sheet_name=None)
      for table, df in dfs.items():
          df.to_sql(table, db)
      

      【讨论】:

      • 如果 excel 是 1k+ 行左右,这不会吃很多 RAM 吗?仍然需要解决方案,谢谢,将探索它!
      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 2011-09-24
      • 2022-01-24
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      相关资源
      最近更新 更多