我需要应用大量的when条件,这些条件通过索引从列表中获取输入。我想问一下,是否有一种方法可以高效地编写代码,在不影响运行时效率的情况下生成相同的结果。
下面是我正在使用的代码
df=df.withColumn('date_match_label', F.when(F.col(date_cols[0])==F.col(date_cols[3]), f"{date_cols[0]} matches with {date_cols[3]}")
.when(F.col(date_cols[0])==F.col(date_cols[3]), f"{date_cols[1]} matches with {date_cols[3]}")
.when(F.col(date_cols[0])==F.col(date_cols[3]), f"{date_cols[1]} matches with {date_cols[3]}")
.when(F.col(date_cols[1])==F.col(date_cols[4]), f"{date_cols[1]} matches with {date_cols[4]}")
.when(F.col(date_cols[1])==F.col(date_cols[4]), f"{date_cols[1]} matches with {date_cols[4]}")
.when(F.col(date_cols[1])==F.col(date_cols[4]), f"{date_cols[1]} matches with {date_cols[4]}")
.when(F.col(date_cols[2])==F.col(date_cols[5]), f"{date_cols[1]} matches with {date_cols[5]}")
.when(F.col(date_cols[2])==F.col(date_cols[5]), f"{date_cols[1]} matches with {date_cols[5]}")
.when(F.col(date_cols[2])==F.col(date_cols[5]), f"{date_cols[1]} matches with {date_cols[5]}")
.otherwise('No Match'))
这里date_cols包含六个列名,我需要检查前三列和后三列,如果匹配,就返回注解。
当前方法的问题是随着列表大小的增加,我不得不添加越来越多的行,这使得我的代码容易出错,看起来很难看。我想知道是否有一种方法,我只需要指定列表索引,需要与其他列表元素进行比较。
1条答案
按热度按时间svgewumm1#
eval
函数,得到的结果如下: