【问题标题】:Introduce a new column in data frame with the value based on condition in PySpark在数据框中引入一个新列,其值基于 PySpark 中的条件
【发布时间】:2020-11-12 03:33:47
【问题描述】:

我有如下 JSON 数据。

    {"images": [
    {
    "alt": null,
    "src": "link_1",
    },
    {
    "alt": null,
    "src": "link_2",
    },
    {
    "alt": "Apple",
    "src": "link_3",
    },
    {
    "alt": null,
    "src": "link_4",
    },
"images": [
    {
    "alt": "Orange",
    "src": "link_1",
    },
    {
    "alt": null,
    "src": "link_2",
    }
]}

我需要通过以下条件在数据框中引入一个具有 src 值 的新列。

  1. 切勿分配第一个位置值。 (例如:link_1)
  2. alt 不应为 NULL,然后将 src 的值分配给新列。如果多个 alt 包含值,则第一个 alt 值被挑选出来,除了位置一。
  3. 如果所有的 alt 都等于 NULL,则将 src 的第二个位置值分配给新列。

注意:图片总是包含多个元素。

对于上面的例子,预期的输出是

+--------------------+
|      new column    |
+--------------------+
|link_3              |
|link_2              |
+--------------------+

任何人都可以帮助获得预期的输出。提前致谢。

【问题讨论】:

  • 你能发布预期的输出吗??
  • 是的,当然.... @Srinivas
  • 所以..你必须......你是怎么做到的? minimal reproducible example?你有什么问题?
  • 更新.......

标签: python-3.x dataframe apache-spark pyspark apache-spark-sql


【解决方案1】:

我今天解决了这个问题。

def extractSecondaryImageUrl(self, *htmlValue):
    for element in htmlValue:
        if len(element) == 0:
            return ''
        if len(element) >= 2:
            element.pop(0)
            for x in element:
                if x['alt'] is not None:
                    return x['src']
            a = element.pop(0)
            return a['src']
        else:
            a = element.pop(0)
            return a['src']

    extractURL = udf(self.extractSecondaryImageUrl, StringType())

    productsDF = productsDF.select("*", extractURL("images").alias('new_column'))

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多