我需要在PySpark的和时使用,否则使用,但不是使用文本,最终值取决于特定列。这是我尝试过的一些代码:
import pyspark.sql.functions as F
def getValueByCountry(country):
# Possibly some more complex calculations based on country
if country == "Spain":
return 1
else:
return 2
def getValue(currency):
# Possibly some more complex calculations based on currency
if currency == "EUR":
return 3
else:
return 4
currency_column = "Currency"
df = df.withColumn(
"Value",
F.when(
F.col(currency_column).contains("None"), getValueByCountry(F.col("Country"))
).otherwise(getValue(F.col(currency_column))),
)
我得到一个错误:
ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.
从“if val=”西班牙“:”行开始。我想这是有意义的,因为我将整个列传递给函数,而不是在每一步传递一个特定的值
有没有一个简单有效的方法来实现我想要的?我听说过使用UDF,但我也看到一些人担心可能出现的性能问题,所以如果有任何不使用UDF的简单方法,我更喜欢它。如果不可能,UDF也可以
这是一些示例输入数据集:
这是执行的输出:
您可以在不使用自定义项的情况下尝试以下操作:
尽管上述内容可能适用于提供的示例,但您可能有更多的值。这样你就可以考虑使用条件运算符:
<> > {{CD1>},用于您尚未考虑的条件。有关spark函数的更多详细信息:here
相关问题 更多 >
编程相关推荐