[英]Turn a spark DataFrame into a list of each row
当前正在接收一个spark数据框,并将其转换为pandas数据框以制成行列表。 我想创建列表而不使其成为熊猫数据框。 Function2将函数应用于每行的字符串表示形式。 列名将不是常数。
def func1(df):
df = df.select("*").toPandas()
job_args = [(", ".join(str(i) for i in list(filter(None.__ne__, df.iloc[c].tolist())))) for c in range(0, len(df))]
results = spark.sparkContext.parallelize(job_args).map(lambda n: function2(n)).collect()
return results
例:
+-----+-----+
|index|count|
+-----+-----+
| 1 | 5 |
| 2 | 9 |
| 3 | 3 |
| 4 | 1 |
成为
rows[0] = [1,5]
rows[1] = [2,9]
rows[2] = [3,3]
rows[3] = [4,1]
如果目标是获取spark数据帧中的所有列并将它们连接为字符串,则可以使用以下两个步骤来实现:
这是一个工作示例,该如何做:
import pyspark.sql.functions as f
l = [(1, 5), (2, 9), (3, 3), (4, 1)]
df = spark.createDataFrame(l, ['index', 'count'])
(
df
.withColumn('arr', f.array(df.columns))
.withColumn('str', f.array_join('arr', ', '))
.select('str')
).show()
+----+
| str|
+----+
|1, 5|
|2, 9|
|3, 3|
|4, 1|
+----+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.