首页 > 解决方案 > IF条件语句在使用Python时不起作用

问题描述

我正在尝试在 2 个条件下执行脚本,如果两个条件都满足,则只能执行进一步的代码。

输入数据: Sheet1

Name        Contact_number  id_number    accuracy
Eric        9786543628      AZ256hy         90
Jack        9786543628      AZ98kds         85
Tom         9784533930      AZ256hc         80
Alan        9778934593      AZ256py         70

表 2

Name        Contact_number  id_number 
Eric        9786543628      AZ256hy  
Jack        9786543628      AZ98kds   
Tom         9784533930      AZ256hc   
David       9778984893      JH657lv 

预期输出:

Name        Contact_number  id_number 
    Eric        9786543628      AZ256hy  
    Jack        9786543628      AZ98kds  

我一直在使用的代码:

df = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet1')
df2 = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet2')

if df['id_number'] = df2['id_number']  and df['accuracy'] =>85:
   df['Name'][index] = df2['Name']
   df['Contact_number'][index] = df2['Contact_number']

但是在使用此条件时,if 语句不适用于AND条件。有什么建议吗?

标签: pythonpandas

解决方案


编辑:我对条件进行了更改。这应该工作

df = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet1')
df2 = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet2')

df.loc[(df['id_number'] == df2['id_number']) & (df['accuracy']>= 85),['Name','Contact_number', 'id_number']]

推荐阅读