【发布时间】:2022-11-29 17:19:45
【问题描述】:
我有一个 PySpark 数据框,其中包含值和为值提供文本映射的字典。 并非每一行都有相同的字典,值也可能不同。
| value | dict |
| -------- | ---------------------------------------------- |
| 1 | {"1": "Text A", "2": "Text B"} |
| 2 | {"1": "Text A", "2": "Text B"} |
| 0 | {"0": "Another text A", "1": "Another text B"} |
我想创建一个包含正确映射的“状态”列。
| value | dict | status |
| -------- | ------------------------------- | -------- |
| 1 | {"1": "Text A", "2": "Text B"} | Text A |
| 2 | {"1": "Text A", "2": "Text B"} | Text B |
| 0 | {"0": "Other A", "1": "Other B"} | Other A |
我试过这段代码:
df.withColumn("status", F.col("dict").getItem(F.col("value"))
此代码不起作用。使用硬编码值,如“2”,相同的代码确实提供了输出,但当然不是正确的输出:
df.withColumn("status", F.col("dict").getItem("2"))
有人可以帮助我在状态列中获得正确的映射值吗?
编辑:我的代码确实有效,除了我的“值”是双精度值并且 dict 中的键是字符串。将列从 double 转换为 int 到 string 时,代码有效。
【问题讨论】:
标签: python dictionary pyspark apache-spark-sql mapping