Pyspark使用带有when和other的函数

2024-09-21 05:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在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也可以

这是一些示例输入数据集:

^{tb1}$

这是执行的输出:

^{tb2}$

Tags: forreturnifdefmorecolumncolsome
1条回答
网友
1楼 · 发布于 2024-09-21 05:25:46

您可以在不使用自定义项的情况下尝试以下操作:

currency_column = "Currency"
df = df.withColumn(
    "Value",
    F.when(
        F.col(currency_column).contains("None"),
        F.when(F.col("Country") == "Spain", 1).otherwise(2),
    ).otherwise(F.when(F.col("Country") == "Russia", 4).otherwise(3)),
)

尽管上述内容可能适用于提供的示例,但您可能有更多的值。这样你就可以考虑使用条件运算符:

currency_column = "Currency"
df = df.withColumn(
    "Value",
    F.when(F.col(currency_column).contains("None") & F.col("Country") == "Spain", 1)
    .when(F.col(currency_column).contains("None") & F.col("Country") == "UK", 2)
    .when(F.col(currency_column) == "USD" & F.col("Country") == "Russia", 4)
    .when(F.col(currency_column) == "EUR" & F.col("Country") == "Netherland", 3)
    .otherwise(999),
)
<> > {{CD1>},用于您尚未考虑的条件。

有关spark函数的更多详细信息:here

相关问题 更多 >

    热门问题