首页 > 解决方案 > 有没有办法区分同名的两列(非连接)

问题描述

这与加入名称重复的问题类似,但无法使用相同的技术来解决,因为所有这些技术都依赖于如何提前规避或准备问题。

因此,在为我的团队准备培训材料时,我添加了一条关于重命名列以使用与另一个列相同的名称的警告,以及 spark 将如何愉快地让你这样做,而不是你最终会得到......

AnalysisException: Reference 'a' is ambiguous, could be: a#1333L, a#1335L.

...当你尝试df.select('a')

所以很明显你应该首先避开问题或修复代码并在它发生时重新运行它,但让我们想象一下假设的情况:

您在一组将长时间计算的转换上工作(在笔记本中以交互方式)并缓存结果。只有在您开始使用缓存的结果之后,您才意识到您犯了一个错字并最终得到两个具有相同名称的列。修复很简单,但重新计算需要很长时间,你的老板正指着手表等待结果......

你做什么工作?

有没有办法修复列名?我可以df.collect()将数据放入 python 并在那里修复它们并重新创建 DF,但是数据很大并且它会杀死驱动程序。我假设您可以降到 RDD 级别并修复它,但我的 RDD 知识非常有限,我不确定是否可以这样。有任何想法吗?

以下是可能导致问题的示例代码:

df.printSchema()
root
 |-- user: integer (nullable = true)
 |-- trackId: integer (nullable = true)
 |-- artistId: integer (nullable = true)
 |-- timestamp: long (nullable = true)

df.withColumnRenamed('timestamp','user').printSchema()
root
 |-- user: integer (nullable = true)
 |-- trackId: integer (nullable = true)
 |-- artistId: integer (nullable = true)
 |-- user: long (nullable = true)


df.withColumnRenamed('timestamp','user').select('user')
AnalysisException: u"Reference 'user' is ambiguous, could be: user#134, user#248L.;"

标签: apache-sparkpyspark

解决方案


这应该有效:

correct_cols = ['user','trackId','artistId','timestamp']
df = df.toDF(*correct_cols)

推荐阅读