是否可以通过数据帧遍历Pyspark组而不进行聚合或计数?
例如熊猫代码:
for i, d in df2:
mycode ....
^^ if using pandas ^^
Is there a difference in how to iterate groupby in Pyspark or have to use aggregation and count?
答案 0 :(得分:1)
当我们进行GroupBy时,我们最终得到一个RelationalGroupedDataset,它是具有指定分组但需要用户指定聚合才能进一步查询的DataFrame的奇特名称。
当您尝试对分组数据框执行任何功能时,会引发错误
AttributeError: 'GroupedData' object has no attribute 'show'
答案 1 :(得分:0)
充其量,您可以使用.first,.last从groupBy中获取各自的值,但并非以获取熊猫的方式全部获取。
例如:
loan_details
由于它们是熊猫处理数据的方式和火花之间的基本区别,因此并非所有功能都可以相同的方式使用。
有一些变通方法可以得到您想要的东西:
对于钻石DataFrame:
from pyspark.sql import functions as f
df.groupBy(df['some_col']).agg(f.first(df['col1']), f.first(df['col2'])).show()
您可以使用:
+---+-----+---------+-----+-------+-----+-----+-----+----+----+----+
|_c0|carat| cut|color|clarity|depth|table|price| x| y| z|
+---+-----+---------+-----+-------+-----+-----+-----+----+----+----+
| 1| 0.23| Ideal| E| SI2| 61.5| 55.0| 326|3.95|3.98|2.43|
| 2| 0.21| Premium| E| SI1| 59.8| 61.0| 326|3.89|3.84|2.31|
| 3| 0.23| Good| E| VS1| 56.9| 65.0| 327|4.05|4.07|2.31|
| 4| 0.29| Premium| I| VS2| 62.4| 58.0| 334| 4.2|4.23|2.63|
| 5| 0.31| Good| J| SI2| 63.3| 58.0| 335|4.34|4.35|2.75|
+---+-----+---------+-----+-------+-----+-----+-----+----+----+----+
输出:
l=[x.cut for x in diamonds.select("cut").distinct().rdd.collect()]
def groups(df,i):
import pyspark.sql.functions as f
return df.filter(f.col("cut")==i)
for i in l:
groups(diamonds,i).show(2)
在功能组中,您可以决定要对数据进行哪种分组。这是一个简单的过滤条件,但它将使您分别获得所有组。