percentage count per group and pivot with pyspark

妖精的绣舞 提交于 2020-01-02 19:41:48

问题


I have dataframe with columns from and to.Both are country codes and they show starting country and destination country.

+----+---+
|from| to|
+----+---+
|  TR| tr|
|  TR| tr|
|  TR| tr|
|  TR| gr|
|  ES| tr|
|  GR| tr|
|  CZ| it|
|  LU| it|
|  AR| it|
|  DE| it|
|  IT| it|
|  IT| it|
|  US| it|
|  GR| fr|

Is there a way to get a dataframe that shows the percentage of each destination country per country of origin, with column all the destination country code?

the percentage must be out of the total destinations by the same country of origin(row).

e.g.

+----+---+----+---+----+
|from| tr|  it| fr|  gr|
+----+---+----+---+----+
|  TR|0.6|0.12|0.2|0.09|
|  IT|0.3| 0.3|0.3| 0.8|
|  US|0.1|0.34|0.3| 0.2|

回答1:


You can pivot with count and adjust the result. First some imports:

from pyspark.sql.functions import col, lit, coalesce
from itertools import chain

Find levels:

levels = [x for x in chain(*df.select("to").distinct().collect())]

pivot:

pivoted = df.groupBy("from").pivot("to", levels).count()

compute row count expression:

row_count = sum(coalesce(col(x), lit(0)) for x in levels)

create a list of adjusted columns:

adjusted = [(col(c) / row_count).alias(c) for c in levels]

and select:

pivoted.select(col("from"), *adjusted)


来源:https://stackoverflow.com/questions/40805808/percentage-count-per-group-and-pivot-with-pyspark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!