gpt4 book ai didi

python - 使用特殊字符映射 Spark 数据帧列

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:32 27 4
gpt4 key购买 nike

执行 df.printSchema() 后,我有以下架构

root
|-- key:col1: string (nullable = true)
|-- key:col2: string (nullable = true)
|-- col3: string (nullable = true)
|-- col4: string (nullable = true)
|-- col5: string (nullable = true)

我需要使用列名称访问键:col2,但由于名称中的 :,以下行给出了错误

df.map(lambda row:row.key:col2)

我已经尝试过

df.map(lambda row:row["key:col2"])

我可以使用以下方法轻松获取 col3、col4 和 col5 的值

df.map(lambda row:row.col4).take(10)

最佳答案

我认为你可以使用getattr:

df.map(lambda row: getattr(row, 'key:col2'))

我不是 pyspark 方面的专家,所以我不知道这是否是最佳方式:-)。

也许还可以使用operator.attrgetter:

from operator import attrgetter
df.map(attrgetter('key:col2'))

IIRC,在某些情况下它的性能优于lambda。在这种情况下,这可能比平常更明显,因为它可以避免全局 getattr 名称查找,在这种情况下,我认为它看起来也更好一些。

关于python - 使用特殊字符映射 Spark 数据帧列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com