首页 > 解决方案 > 获取最小值关联国家

问题描述

我有一个包含国家、地区、价值、产品的数据集。需要将 min_x 和 region-country 与 min-value 作为单独的列

数据集

cust    Country Region  value   product
 100    france  europe   1       x
 101    france  europe   2       x
 102    poland  europe   3       x
 103    poland  europe   3       y
 104    france  europe   4       y
 105    france  europe   5       y

我想要所有客户的每种产品的最小值。为此,我按产品分组。

cust    Country Region  value   product min_x
 100    france  europe  1   x   1
 101    france  europe  2   x   1
 102    poland  europe  3   x   1
 103    poland  europe  3   y   3
 104    france  europe  4   y   3
 105    france  europe  5   y   3



 df = spark.read.csv('dataset',header=True)
 df1 = df.groupBy('Product').agg(min(df.value).alias('min_x))

需要一个带有区域国家的列,其 min_value 为 x。加入时无法获取国家和地区的值。

标签: pyspark

解决方案


我找到了解决方案。

df = spark.read.csv(path,header=True)
w1 = Window.partitionBy(df.product).orderBy(df.value.desc())
df = df.withColumn('min_x',min(df.value).over(w1)).\
        withColumn('region_country',concat_ws('_',first('region'),first('country')))

推荐阅读