有没有一种方法可以使用 Python 在 Excel 中执行 Select 语句,例如 SQL?
Is there a way to do a Select statement like SQL in Excel using Python?
鉴于此 excel sheet:
Excel File
假设 SQL Select 语句如下所示:
Select Status from sheet where name = "John Doe" and age = 20
和 return 匹配 name/age 的行的状态值
excel 也可以有超过 1 行。
我还添加了 excel 的复制粘贴,但它粘贴了一张图片,我不确定如何分享实际的 excel 内容
您可以使用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
首先,加载您的 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"])
如果您想使用纯 SQL 请求来查询您的 Excel 文件,您首先需要将其转换为数据库。最简单的解决方案是 sqlite
,因为它是 Python 标准库的一部分,不需要设置 DBMS,结合 pandas
。您可以在 .
中找到示例
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 sheet: Excel File
假设 SQL Select 语句如下所示:
Select Status from sheet where name = "John Doe" and age = 20
和 return 匹配 name/age 的行的状态值 excel 也可以有超过 1 行。
我还添加了 excel 的复制粘贴,但它粘贴了一张图片,我不确定如何分享实际的 excel 内容
您可以使用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
首先,加载您的 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"])
如果您想使用纯 SQL 请求来查询您的 Excel 文件,您首先需要将其转换为数据库。最简单的解决方案是 sqlite
,因为它是 Python 标准库的一部分,不需要设置 DBMS,结合 pandas
。您可以在
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)