简体   繁体   English

如何使用 python 在条件语句中执行脚本

[英]How to execute an script within an conditional statement using python

I am looking to execute the script within an conditional statement, I have also tried to use the script within an function but its not working我希望在条件语句中执行脚本,我也尝试在 function 中使用脚本,但它不起作用

ValueError: The truth value of a Series is ambiguous. ValueError:Series 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

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

if df1['id_number'] != NaN:
  cross = df1[['id_number']].merge(df2[['identity_no']], how='cross')
  cross['match_acc'] = cross.apply(lambda x: fuzz.ratio(x.id_number, x.identity_no), axis=1)
  df1['match_acc'] = df1.id_number.map(cross.groupby('id_number').match_acc.max()) 

Is there any other way to execute the script under the given condition.在给定条件下是否有任何其他方法可以执行脚本。 Can we use the conditional statement by creating an function.我们可以通过创建 function 来使用条件语句吗?

def conn(x):
  cross = df1[['id_number']].merge(df2[['identity_no']], how='cross')
  cross['match_acc'] = cross.apply(lambda x: fuzz.ratio(x.id_number, x.identity_no), axis=1)
  df1['match_acc'] = df1.id_number.map(cross.groupby('id_number').match_acc.max()) 

Please Suggest.请建议。

In if df1['id_number']:= NaN: you are comparing a series to a single value (scalar) of NaN .if df1['id_number']:= NaN:中,您将一系列与NaN的单个值(标量)进行比较。 This will create a boolean array of True / False values.这将创建一个包含True / False值的 boolean 数组。 You need to specify whether you want any of those values to be True , or all of the values:您需要指定是否希望这些值中的任何一个为True或所有值:

if df1['id_number'].notna().any(): # any one value has to be != NaN

or或者

if df1['id_number'].notna().all(): # all have to be != NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM