【问题标题】:How to pass list to the selectExpr method in pyspark?如何将列表传递给pyspark中的selectExpr方法?
【发布时间】:2021-12-01 11:12:07
【问题描述】:

问题看似简单,却找不到简单的解决方法。

我正在尝试在selectExpr 中动态创建新列,但它不接受列表作为参数。实现它的最佳方法是什么? (多个withColumn 不是一个选项,因为stackoverflowexception 输入:

a | b
-------
1 | zzz
2 | xxx

试过这样的

sample_new_cols = {"s":"ran-s", 
                  "ts": "current_timestamp()",
                  }

 df = df.selectExpr('*',
            [
                f"{definition} as {name}"
                for name, definition in sample_new_cols.items()
            ]
        )

它的输出是

a | b | s   | ts 
------------|-----------
1 |zzz|ran-s|2021-12-01 08:10:21
2 |xxx|ran-s|2021-12-01 08:10:21

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql


    【解决方案1】:

    你几乎明白了:

    • 对于字符串静态列定义,您需要引用值(例如'ran-s'
    • selectExpr 中,您需要在列数组之前使用星号*
    sample_new_cols = {
        "s": "'ran-s'",
        "ts": "current_timestamp()",
    }
    
    df1 = df.selectExpr('*', *[
        f"{definition} as {name}"
        for name, definition in sample_new_cols.items()
    ])
    
    df1.show()
    
    #+---+---+-----+-----------------------+
    #|a  |b  |s    |ts                     |
    #+---+---+-----+-----------------------+
    #|1  |zzz|ran-s|2021-12-01 14:23:14.779|
    #|2  |xxx|ran-s|2021-12-01 14:23:14.779|
    #+---+---+-----+-----------------------+
    

    【讨论】:

    • 哈,谢谢@blackbishop。我在发布的几分钟内将其整理出来,然后完全忘记了我在这里问过的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2017-08-06
    • 2020-09-07
    • 1970-01-01
    • 2020-11-14
    • 2018-10-29
    相关资源
    最近更新 更多