我有一个包含国家,地区,价值,产品的数据集。需要获取具有最小值的min_x和区域国家/地区作为 sperate 列
数据
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))
需要再增加一个带有x min_value的区域-国家/地区的列,加入时无法获取国家和地区的值。
我找到了解决方案。
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')))