升级第1行作为列标题-Spark DataFrame

问题描述

我低于Spark数据框。

enter image description here

我想将第1行提升为列标题,而新的spark DataFrame应该是

enter image description here

我知道这很容易在熊猫中完成,

new_header =  pandaDF.iloc[0]
pandaDF = pandaDF[1:]
pandaDF.columns = new_header

但是不想转换为Pandas DF,因为必须将其持久化到数据库中,其中必须将Pandas DF转换回Spark Spark DF,然后注册为表,然后写入db。

解决方法

尝试使用 .toDF filter 我们的列值。

Example:

#sample dataframe
df.show()
#+----------+------------+----------+
#|    prop_0|      prop_1|    prop_2|
#+----------+------------+----------+
#|station_id|station_name|sample_num|
#|       101|  Station101| Sample101|
#|       102|  Station102| Sample102|
#+----------+------------+----------+

from pyspark.sql.functions import *

cols=sc.parallelize(cols).map(lambda x:x).collect()

df.toDF(*cols).filter(~col("station_id").isin(*cols)).show()
#+----------+------------+----------+
#|station_id|station_name|sample_num|
#+----------+------------+----------+
#|       101|  Station101| Sample101|
#|       102|  Station102| Sample102|
#+----------+------------+----------+