Python 函数与可选的 "and" 条件
Python function with optional "and" condition
我正在尝试弄清楚是否可以将以下 2 个相似的函数组合成 1 个(这更多是从实际角度出发 - 以更容易处理的为准)。如果是,那么 如何?
get_result_1()
: 总是需要
get_result_2()
: get_result_1()
+ 带有变量的“and”语句 column_name & input_value
有问题的函数:
def get_result_1(item: str, type: str) -> Column:
c = ((f.col("item") == item) & (f.col("type") == type))
return c
def get_result_2(item: str, type: str, input_1: str, input_2: str) -> Column:
c = (get_result_1(item, type)
& (f.col(input_1) == input_2) #<-- make this part of get_result_1?
)
return c
用例:
output_df = (
df
.withColumn("category",
f.when(get_result_1("A", "xyz1"), f.lit("C1"))
.when(get_result_2("B", "xyz2", "level1", "high"), f.lit("C2"))
.when(get_result_2("B", "xyz3", "level2", "L7"), f.lit("C3"))
)
)
我一直在探索可变参数,但我无法让它发挥作用。在这一点上,我怀疑我是否走在正确的道路上。
从 Spark 方面来看,这无关紧要,因为无论哪种方式,它都应该产生相同的查询。您可以使用这两种方法通过 df.explain()
检查这一点。
您可以通过使 input_1
和 input_2
可选并检查它们是否通过来组合这两个函数。如果您愿意,可以添加一些额外的检查。
def get_result(item: str, item_type: str, input_1: str = None, input_2: str = None) -> Column:
c = ((f.col("item") == item) & (f.col("type") == item_type))
if input_1:
c = c & (f.col(input_1) == input_2)
return c
我正在尝试弄清楚是否可以将以下 2 个相似的函数组合成 1 个(这更多是从实际角度出发 - 以更容易处理的为准)。如果是,那么 如何?
get_result_1()
: 总是需要get_result_2()
:get_result_1()
+ 带有变量的“and”语句 column_name & input_value
有问题的函数:
def get_result_1(item: str, type: str) -> Column:
c = ((f.col("item") == item) & (f.col("type") == type))
return c
def get_result_2(item: str, type: str, input_1: str, input_2: str) -> Column:
c = (get_result_1(item, type)
& (f.col(input_1) == input_2) #<-- make this part of get_result_1?
)
return c
用例:
output_df = (
df
.withColumn("category",
f.when(get_result_1("A", "xyz1"), f.lit("C1"))
.when(get_result_2("B", "xyz2", "level1", "high"), f.lit("C2"))
.when(get_result_2("B", "xyz3", "level2", "L7"), f.lit("C3"))
)
)
我一直在探索可变参数,但我无法让它发挥作用。在这一点上,我怀疑我是否走在正确的道路上。
从 Spark 方面来看,这无关紧要,因为无论哪种方式,它都应该产生相同的查询。您可以使用这两种方法通过 df.explain()
检查这一点。
您可以通过使 input_1
和 input_2
可选并检查它们是否通过来组合这两个函数。如果您愿意,可以添加一些额外的检查。
def get_result(item: str, item_type: str, input_1: str = None, input_2: str = None) -> Column:
c = ((f.col("item") == item) & (f.col("type") == item_type))
if input_1:
c = c & (f.col(input_1) == input_2)
return c