![](/img/trans.png)
[英]how to plot a pie chart from a dataframe using crosstab function in python
[英]How to obtain row percentages of crosstab from a spark dataframe using python?
只需使用withColumn
和您的公式添加 2 列来计算百分比:
from pyspark.sql import functions as F
df1 = df.stat.crosstab("age", "y").orderBy("age_y")
result = df1.withColumn(
"no_rp",
F.round(F.col("no") / (F.col("no") + F.col("yes")) * 100, 2)
).withColumn(
"yes_rp",
F.round(F.col("yes") / (F.col("no") + F.col("yes")) * 100, 2)
)
result.show()
#+-----+---+---+-----+------+
#|age_y| no|yes|no_rp|yes_rp|
#+-----+---+---+-----+------+
#| 18| 5| 7|41.67| 58.33|
#| 19| 24| 11|68.57| 31.43|
#| 20| 35| 15| 70.0| 30.0|
#+-----+---+---+-----+------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.