![](/img/trans.png)
[英]Want to check certain values are present in the excel sheet with python
[英]I want to Check if the values present on a certain column from sheet1 are also present on sheet2 using Python
几周前,我开始了我的 Python 旅程。 我的主要目标是能够自动化我日常工作的某些方面,并在未来更多地研究数据科学。 现在,我正在尝试制作一个脚本,该脚本将检查 sheet1 中某个列上存在的值是否也存在于 sheet2 上。 我设法到达这里:
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
pd.set_option('display.max_columns', 500)
df = pd.ExcelFile('C:\\Users\\Andre\\Desktop\\Scraps\\abacus.xlsx')
sheet1 = pd.read_excel(df, 'Sheet1')
sheet2 = pd.read_excel(df, 'Sheet2')
print(type(df))
print(sheet1)
print(sheet2)
df['Ref'] = df.lookup(df.index, df[sheet2['Ref']])
我知道我的最后一行不正确,但它也指出“ExcelFile”object 没有属性“lookup”,所以我无法找到探索的路径。 有人可以给我指个方向吗?
考虑到您的代码:
df = pd.ExcelFile('C:\\Users\\Andre\\Desktop\\Scraps\\abacus.xlsx')
sheet1 = pd.read_excel(df, 'Sheet1')
sheet2 = pd.read_excel(df, 'Sheet2')
这里, sheet1
和sheet2
是各个工作表的数据框。
您想要检查 sheet1 的特定列值是否存在于 sheet2 的同一列中。
考虑下面的例子:
In [1898]: sheet1
Out[1898]:
id_col1 id_col2 name age sex
0 101 1M NaN 21 NaN
1 101 3M NaN 21 M
2 102 1M Mark 25 NaN
In [1899]: sheet2
Out[1899]:
id_col1 id_col2 name age sex
0 101 1M Steve NaN M
1 101 2M NaN NaN M
2 101 3M Steve 25.0 None
3 102 1M Ria 25.0 M
4 102 2M Anie 22.0 F
从上面的数据帧中,列id_col1
存在于 sheet1 和 sheet2 中。
因此,让我们检查一下 sheet1 中id_col1
的所有值是否都存在于 sheet2 的id_col1
中。
In [1900]: sheet1['id_col1'].isin(sheet2['id_col1'])
Out[1900]:
0 True
1 True
2 True
Name: id_col1, dtype: bool
您可以有一个for
循环并对所有列执行相同的操作:
In [1902]: for col in sheet1.columns.tolist():
...: print(sheet1[col].isin(sheet2[col]))
...:
0 True
1 True
2 True
Name: id_col1, dtype: bool
0 True
1 True
2 True
Name: id_col2, dtype: bool
0 True
1 True
2 False
Name: name, dtype: bool
0 False
1 False
2 True
Name: age, dtype: bool
0 False
1 True
2 False
Name: sex, dtype: bool
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.