我有一个大数据框,数据框包含一组人,这些人在变量中标记为" groups"。
现在我需要为这个数据框做些什么,以更有意义的方式呈现。
例如,在以下组148中,这是下表:
df.select('gender','postcode','age','groups','bought').filter(df.groups==148).show()
+------+--------+---+----------+----------+
|gender|postcode|age| groups|bought |
+------+--------+---+----------+----------+
| 0| 2189| 25| 148|car |
| 0| 2192| 34| 148|house |
| 1| 2193| 37| 148|car |
| 1| 2194| 38| 148|house |
| 1| 2196| 54| 148|laptop |
| 1| 2197| 27| 148|laptop |
| 0| 2198| 44| 148|laptop |
+------+--------+---+----------+----------+
性别有0,1,所以这一群人中的所有人都将被改为"人" 如果全部为1,则为女性,如果全部为0则为男性。规则,但不适用于这个群体。
现在邮政编码,最低的是2189,最高的是2211,然后每个案例都会改为[2189 - 2198]。
对于年龄,最低为18,最高为62,因此它将为[25-54]
买了,我需要检查哪些物品已经买了,这些是[汽车,房子,笔记本电脑]
因此,这组重新编码将最终为:
+------+-------------+--------+----------+------------------+
|gender| postcode| age| groups| bought |
+------+-------------+--------+----------+------------------+
|person|[2189 - 2198]| [25-54]| 148|[car,house,laptop]|
|person|[2189 - 2198]| [25-54]| 148|[car,house,laptop]|
|person|[2189 - 2198]| [25-54]| 148|[car,house,laptop]|
|person|[2189 - 2198]| [25-54]| 148|[car,house,laptop]|
|person|[2189 - 2198]| [25-54]| 148|[car,house,laptop]|
|person|[2189 - 2198]| [25-54]| 148|[car,house,laptop]|
|person|[2189 - 2198]| [25-54]| 148|[car,house,laptop]|
+------+-------------+--------+----------+------------------+
将在数据框中为所有组完成。
有什么想法吗? Here我发现了类似的东西但是在scala中 提前谢谢!
答案 0 :(得分:2)
希望这有帮助!
import pyspark.sql.functions as f
from pyspark.sql.types import StringType
df = sc.parallelize([
[0, 2189, 25, 148, 'car'],
[0, 2192, 34, 148, 'house'],
[1, 2193, 37, 148, 'car'],
[1, 2194, 38, 148, 'house'],
[1, 2196, 54, 148, 'laptop'],
[1, 2197, 27, 148, 'laptop'],
[0, 2198, 44, 148, 'laptop']
]).toDF(('gender', 'postcode', 'age', 'groups', 'bought'))
df.show()
df1 = df.groupBy("groups").agg(f.collect_set("bought")).withColumnRenamed("collect_set(bought)","bought")
df2 = df.groupBy("groups").agg(f.min("age"), f.max("age")). \
withColumn("age", f.concat(f.col("min(age)"), f.lit("-"), f.col("max(age)"))).select("groups","age")
df3 = df.groupBy("groups").agg(f.min("postcode"), f.max("postcode")). \
withColumn("postcode", f.concat(f.col("min(postcode)"), f.lit("-"), f.col("max(postcode)"))).select("groups","postcode")
def modify_values(l):
if l == [0, 1]:
return "person"
else:
if l == [0]:
return "male"
else:
return "female"
modified_val = f.udf(modify_values, StringType())
df4 = df.groupBy("groups").agg(f.collect_set("gender")).withColumn("gender",modified_val("collect_set(gender)")).select("groups","gender")
merged_df = df1.join(df2, "groups").join(df3, "groups").join(df4, "groups")
merged_df.show()
输出是:
+------+--------------------+-----+---------+------+
|groups| bought| age| postcode|gender|
+------+--------------------+-----+---------+------+
| 148|[laptop, house, car]|25-54|2189-2198|person|
+------+--------------------+-----+---------+------+
如果它解决了您的问题,请不要告诉我们