【问题标题】:round results in aggregate table results (pyspark)汇总表结果中的舍入结果(pyspark)
【发布时间】:2019-10-29 21:35:20
【问题描述】:

您好,我将如何对这段代码输出的表格内容进行四舍五入。

from pyspark.sql.functions import *
exprs = {x: "sum" for x in data2.columns[:4]}
data2.groupBy("Species").agg(exprs).show() 

我试过了

round(data2.groupBy("Species").agg(exprs),2).show() #not ok

data2.groupBy("Species").agg(exprs).show().round(2) # not ok

【问题讨论】:

    标签: pyspark aggregate iris-dataset


    【解决方案1】:

    round 仅适用于一列。所以你必须为每一列调用它,例如

    agg_cols = data2.columns[:4]
    exprs = [sum(col(x)).alias(x) for x in agg_cols]
    aggregated_df = data2.groupBy("Species").agg(*exprs)
    aggregated_df.select(col("Species"), *[round(c, 2) for c in agg_cols]).show() 
    

    【讨论】:

    • 我收到了这个错误TypeError: Column is not iterable
    • 在哪一行?你能检查一下 agg_cols 是一个字符串列表吗?
    • 是的 agg_cols 是字符串列表。它来自这条线。 aggregated_df = data2.groupBy("Species").agg(exprs)
    • 我已经编辑了答案。请再试一次好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2015-06-27
    • 2011-09-30
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多