Pyspark - 如何根据查找 table 重命名列名?

Pyspark - How can i rename column names based on a lookup table?

我有两个table如下:

Table 1:

Table 2:

我想用 table 2 中的日期列替换 Table 1 的名称。

最终输出应该如下所示 table:

感谢所有帮助!

谢谢!

我假设 table 2 不是那么大,考虑到它们是列名映射,否则将它们带到驱动程序时会出现内存问题。试试这个。

tst1=sqlContext.createDataFrame([(1,2,3,4,5,6,7,8),(5,6,7,8,9,10,11,12),(13,14,15,16,17,18,19,20)],["a","b","c","d","e","f","g","h"])
tst2=sqlContext.createDataFrame([('a','apple'),('b','ball'),('c','cat'),('d','dog'),('e','elephant'),('f','fox'),('g','goat'),('h','hat')],["short","long"])
tst1.show()
+---+---+---+---+---+---+---+---+
|  a|  b|  c|  d|  e|  f|  g|  h|
+---+---+---+---+---+---+---+---+
|  1|  2|  3|  4|  5|  6|  7|  8|
|  5|  6|  7|  8|  9| 10| 11| 12|
| 13| 14| 15| 16| 17| 18| 19| 20|
+---+---+---+---+---+---+---+---+
# Collect the table 2 to extract the mapping
tst_cl = tst2.collect()
# get the old and new names of the columns
old_name=[str(tst_cl[i][0]) for i in range(len(tst_cl))]
new_name=[str(tst_cl[i][1]) for i in range(len(tst_cl))]
# Rename the columns
tst_rn = tst1.select(old_name).toDF(*new_name)
tst_rn.show()
+-----+----+---+---+--------+---+----+---+
|apple|ball|cat|dog|elephant|fox|goat|hat|
+-----+----+---+---+--------+---+----+---+
|    1|   2|  3|  4|       5|  6|   7|  8|
|    5|   6|  7|  8|       9| 10|  11| 12|
|   13|  14| 15| 16|      17| 18|  19| 20|
+-----+----+---+---+--------+---+----+---+

收集列映射后,您可以使用此处使用的任何重命名技术:

提示:如果你在收集期间遇到一些顺序不匹配问题(大多数情况下你不会,但如果你想三重确定)然后考虑使用 [=19= 在 table 2 中组合映射]() 方法,然后收集。映射必须稍微改变

tst_array= tst2.withColumn("name_array",F.array(F.col('short'),F.col('long')))
tst_clc = tst_array.collect()
old_name = [str(tst_clc[i][2][0]) for i in range(len(tst_clc))]
new_name = [str(tst_clc[i][2][1]) for i in range(len(tst_clc))]