它可以在没有聚合或计数的情况下遍历 Pyspark groupBy 数据帧吗?
例如 Pandas 中的代码示例:
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?
充其量你可以使用 .first , .last 从 groupBy 获取相应的值,但不能像在熊猫中那样获取全部值。
前任:
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 multi grouping
def groups_multi(df,i):
import pyspark.sql.functions as f
return df.filter((f.col("cut")==i) & (f.col("color")=='E'))# use | for or.
for i in l:
groups(diamonds,i).show(2)
输出:
+---+-----+-------+-----+-------+-----+-----+-----+----+----+----+
|_c0|carat| cut|color|clarity|depth|table|price| x| y| z|
+---+-----+-------+-----+-------+-----+-----+-----+----+----+----+
| 2| 0.21|Premium| E| SI1| 59.8| 61.0| 326|3.89|3.84|2.31|
| 4| 0.29|Premium| I| VS2| 62.4| 58.0| 334| 4.2|4.23|2.63|
+---+-----+-------+-----+-------+-----+-----+-----+----+----+----+
only showing top 2 rows
+---+-----+-----+-----+-------+-----+-----+-----+----+----+----+
|_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|
| 12| 0.23|Ideal| J| VS1| 62.8| 56.0| 340|3.93| 3.9|2.46|
+---+-----+-----+-----+-------+-----+-----+-----+----+----+----+
...
在函数组中,您可以决定要对数据进行哪种分组。这是一个简单的筛选条件,但它将分别获取所有组。
当我们执行 GroupBy 时,我们最终会得到一个 RelationalGroupedDataset,这是一个指定了分组但需要用户指定聚合才能进一步查询的数据帧的奇特名称。
当您尝试在分组数据帧上执行任何功能时,它会引发错误
AttributeError: 'GroupedData' object has no attribute 'show'
是的,不要使用分组依据,而是使用不同的选择。
df.select("col1", "col2", ...).distinct()
然后,您可以执行任意数量的事情来循环访问数据帧。
即 1-将PySpark DF转换为熊猫。
DataFrame.toPandas()
2-如果您的DF很小,您可以将其转换为列表。
DataFrame.collect()
3-应用带有foreach(your_method(的方法。
Dataframe.foreach(your_method)
4-转换为RDD并使用带有lambda的映射。
DataFrame.rdd.map(lambda x: your_method(x))