【问题标题】:Store count as variable and use it for calculations in PySpark将计数存储为变量并将其用于 PySpark 中的计算
【发布时间】:2021-08-20 02:01:35
【问题描述】:

我有数据框 df1:

+------+-----------+----------+----------+-----+
|   sid|acc_term_id|first_name| last_name|major|
+------+-----------+----------+----------+-----+
|106454|      2014B|     Doris|  Marshall|  BIO|
|106685|      2015A|      Sara|Richardson|  CHM|
|106971|      2015B|      Rose|    Butler|  CHM|
|107298|      2015B|     Kayla|    Barnes|  CSC|
|107555|      2016A|   Carolyn|      Ford|  PHY|
|107624|      2016B|     Marie|      Webb|  BIO|

我想存储这个数据帧中的 sid 计数

c_value = current.agg({"sid": "count"}).collect()[0][0]

并使用它来创建 prop 列,如下面的代码所示:

    c_value = current.agg({"sid": "count"}).collect()[0][0]
stud_major = (
    current
    .groupBy('major')
    .agg(
    expr('COUNT(*) AS n_students')
    
    )
    .select('major', 'n_students', expr('ROUND(n_students/c_value, 4) AS prop'),
    )
)

stud_major.show(16)

当我运行代码时出现错误:

cannot resolve '`c_value`' given input columns: [major, n_students]; line 1 pos 17;

如果我输入数值 2055 而不是 c_value 一切正常,如下所示。

+

-----+----------+------+
|major|n_students|  prop|
+-----+----------+------+
|  MTH|       320|0.1557|
|  CHM|       405|0.1971|
|  CSC|       508|0.2472|
|  BIO|       615|0.2993|
|  PHY|       207|0.1007|
+-----+----------+------+

可能还有其他计算方法,但我需要将 count 存储为 variable

有什么想法吗?

【问题讨论】:

  • 你能给出预期输出的样本吗?
  • @wwnde 是已编辑的问题
  • Pandas df.groupby("major")['sid'].agg(n_students=(lambda x: x.count()), pop=(lambda x: x.count()/df.agg({'sid':'count'}))) 你的号码不代表
  • @wwnde 我需要将计数存储为变量
  • 好的,你想要的答案是什么?

标签: sql pandas variables filter pyspark


【解决方案1】:

在 jupyter 中使用 pandas agg

j=df.agg({'sid':'count'})
df.groupby("major")['sid'].agg(n_students=(lambda x: x.count()), prop=(lambda x: x.count()/j))



    major  n_students  prop
0   BIO           2  0.333333
1   CHM           2  0.333333
2   CSC           1  0.166667
3   PHY           1  0.166667

和 pyspark

  from pyspark.sql.functions import *
df.groupby('major').agg(count('sid').alias('n_students')).withColumn('prop', round((col('n_students')/c_value),2)).show()

你也可以

c_value = df.agg({"sid": "count"}).collect()[0][0]




df.groupBy('major').agg(expr('COUNT(*) AS n_students')).selectExpr('major',"n_students", f"ROUND(n_students/{c_value},2) AS prop").show()

+-----+----------+----+
|major|n_students|prop|
+-----+----------+----+
|  BIO|         2|0.33|
|  CHM|         2|0.33|
|  CSC|         1|0.17|
|  PHY|         1|0.17|
+-----+----------+----+

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多