使用 withcolumn 迭代具有静态值列表的 spark 数据框

Iterate a spark dataframe with static list of values using withcolumn

我对 pyspark 有点陌生。我有一个包含大约 5 列和 5 条记录的 spark 数据框。我有 5 条记录的列表。 现在我想使用 withColumn 将列表中的这 5 条静态记录添加到现有数据框中。我这样做了,但它不起作用。 非常感谢任何建议。

下面是我的示例:

dq_results=[] 

for a in range(0,len(dq_results)):
    dataFile_df=dataFile_df.withColumn("dq_results",lit(dq_results[a]))
    print lit(dq_results[a])

谢谢, 斯里拉姆

withColumn 将添加一个新的列,但我想您可能想要附加行。试试这个:

df1 = spark.createDataFrame([(a, a*2, a+3, a+4, a+5) for a in range(5)], "A B C D E".split(' '))

new_data = [[100 + i*j for i in range(5)] for j in range(5)]

df1.unionAll(spark.createDataFrame(new_data)).show()

+---+---+---+---+---+
|  A|  B|  C|  D|  E|
+---+---+---+---+---+
|  0|  0|  3|  4|  5|
|  1|  2|  4|  5|  6|
|  2|  4|  5|  6|  7|
|  3|  6|  6|  7|  8|
|  4|  8|  7|  8|  9|
|100|100|100|100|100|
|100|101|102|103|104|
|100|102|104|106|108|
|100|103|106|109|112|
|100|104|108|112|116|
+---+---+---+---+---+
dq_results=[] 

从列表dq_results创建一个数据框:

df_list=spark.createDataFrame(dq_results_list,schema=dq_results_col)

为 df_list id 添加一列(它将是行 id)

df_list_id = df_list.withColumn("id", monotonically_increasing_id())

为 dataFile_df id 添加一列(它将是行 id)

dataFile_df= df_list.withColumn("id", monotonically_increasing_id())

现在我们可以连接两个数据框 df_listdataFile_df

dataFile_df.join(df_list,"id").show()

所以dataFile_df是最终数据帧