首页 > 解决方案 > 如何将 Pyspark 数据框标头设置为另一行?

问题描述

我有一个看起来像这样的数据框:

# +----+------+---------+
# |col1| col2 |  col3   |
# +----+------+---------+
# |  id| name |    val  |
# |  1 |  a01 |    X    |
# |  2 |  a02 |    Y    |
# +---+-------+---------+

我需要从中创建一个新的数据框,使用 row[1] 作为新的列标题并忽略或删除 col1、col2 等行。新表应如下所示:

# +----+------+---------+
# | id | name |   val   |
# +----+------+---------+
# |  1 |  a01 |    X    |
# |  2 |  a02 |    Y    |
# +---+-------+---------+

列可以是可变的,因此我不能使用名称在新数据框中显式设置它们。这不使用熊猫df。

标签: pythonapache-sparkpyspark

解决方案


id假设在 col1namecol2valcol3中只有一行,您可以使用以下逻辑(为了清晰和解释而注释)

#select the row with the header name 
header = df.filter((df['col1'] == 'id') & (df['col2'] == 'name') & (df['col3'] == 'val'))

#selecting the rest of the rows except the first one 
restDF = df.subtract(header)

#converting the header row into Row 
headerColumn = header.first()

#looping columns for renaming 
for column in restDF.columns:
    restDF = restDF.withColumnRenamed(column, headerColumn[column])

restDF.show(truncate=False)

这应该给你

+---+----+---+
|id |name|val|
+---+----+---+
|1  |a01 |X  |
|2  |a02 |Y  |
+---+----+---+

但是最好的选择是在使用sqlContext从源代码读取数据帧时,将header 选项设置为 true来读取它


推荐阅读