使用 pandas 和 openpyxl 匹配工作簿的 2 excel 张中的值
Matching values in 2 excel sheets of a workbook using pandas and openpyxl
我的 xlsx 文件中有 2 个 sheet。该文件存储在本地。当我打印行和列时,我得到了输出。我想要的是,如果 "patient info" sheet 的第一列(患者 ID)中的任何值与 "records" sheet 的第一列(p id)中的任何值匹配,那么我想要将 "records" sheet 中的单元格值附加到列表 c 并打印所有匹配列表 values.But 当我 运行 宁我的代码时,没有生成输出甚至当它是 运行 时没有显示错误或警告。请找到附件中的数据集。patients dataset
import openpyxl
import pandas as pd
filename="week_05_homework_XLSX_openpyxl.xlsx"
wb= openpyxl.load_workbook(filename)
sheet1=wb['patient info']
sheet2=wb['records']
df1= pd.DataFrame(sheet1.values)
df2= pd.DataFrame(sheet2.values)
p=len(df1.index)
q=len(df2.index)
c =[]
for i in range(2,p):
for j in range(2,q):
if df1.iloc[i,1]==df2.iloc[j,1]:
c.append((df2.iloc[j,1]))
print(c)
如果您只想从两个数据框中获取公共 ID,则仅使用交集运算来查找公共 ID 可能会更快更清晰。这个答案可能会有帮助:
如果没有,您可以随时打印它们,然后打印通用 ID 作为结尾。
一种方法是将 ID 设置为索引,然后:
common_ids = df1.index.intersection(df2.index)
c = records.iloc[common_ids,:]
我的 xlsx 文件中有 2 个 sheet。该文件存储在本地。当我打印行和列时,我得到了输出。我想要的是,如果 "patient info" sheet 的第一列(患者 ID)中的任何值与 "records" sheet 的第一列(p id)中的任何值匹配,那么我想要将 "records" sheet 中的单元格值附加到列表 c 并打印所有匹配列表 values.But 当我 运行 宁我的代码时,没有生成输出甚至当它是 运行 时没有显示错误或警告。请找到附件中的数据集。patients dataset
import openpyxl
import pandas as pd
filename="week_05_homework_XLSX_openpyxl.xlsx"
wb= openpyxl.load_workbook(filename)
sheet1=wb['patient info']
sheet2=wb['records']
df1= pd.DataFrame(sheet1.values)
df2= pd.DataFrame(sheet2.values)
p=len(df1.index)
q=len(df2.index)
c =[]
for i in range(2,p):
for j in range(2,q):
if df1.iloc[i,1]==df2.iloc[j,1]:
c.append((df2.iloc[j,1]))
print(c)
如果您只想从两个数据框中获取公共 ID,则仅使用交集运算来查找公共 ID 可能会更快更清晰。这个答案可能会有帮助:
如果没有,您可以随时打印它们,然后打印通用 ID 作为结尾。
一种方法是将 ID 设置为索引,然后:
common_ids = df1.index.intersection(df2.index)
c = records.iloc[common_ids,:]