【发布时间】:2021-03-24 22:32:01
【问题描述】:
我解释说spark sum function 可以使用字符串列名。但是,当使用 column name 或 column object 时,我会看到不同的结果。
schema = ["department", "employee", "knwos_ops", "developer"]
data = [("frontend", "john", 0, 1,), ("frontend", "jenny", 1, 1,), ("frontend", "michael", 0, 1,)]
input_df = spark.createDataFrame(data, schema=schema)
input_df.show(5, False)
+----------+--------+---------+---------+
|department|employee|knwos_ops|developer|
+----------+--------+---------+---------+
|frontend |john |0 |1 |
|frontend |jenny |1 |1 |
|frontend |michael |0 |1 |
+----------+--------+---------+---------+
input_df \
.groupBy(*["department"]) \
.agg( \
f.sum("developer").alias("dev"), \
f.sum(f.when(f.col("knwos_ops") == 1, "developer")).alias("devops"), \
f.sum("knwos_ops").alias("ops"),
).show(5, False)
+----------+---+------+---+
|department|dev|devops|ops|
+----------+---+------+---+
|frontend |3 |null |1 |
+----------+---+------+---+
input_df \
.groupBy(*["department"]) \
.agg( \
f.sum("developer").alias("developer"), \
f.sum(f.when(f.col("knwos_ops") == 1, f.col("developer"))).alias("devops"), \
f.sum("knwos_ops").alias("ops"),
).show(5, False)
+----------+---+------+---+
|department|dev|devops|ops|
+----------+---+------+---+
|frontend |3 |1 |1 |
+----------+---+------+---+
我对函数sum和when的理解如下,
- 函数
when如果条件匹配则返回值,否则返回null。 - 函数
sum使用字符串类型的列名或Column类型的列名。
基于此,在第一个聚合示例中,when 函数内的条件应将列 developer 名称作为字符串返回,函数 sum 应使用该字符串进行聚合并返回 2。但是它返回 null。
为什么 spark 无法识别 developer 是数据框的一列。有人可以帮我理解这背后的文档吗?
更新
谢谢热心回复。正如我在第二次聚合中所做的那样,我有办法解决这个问题。我宁愿寻找这种行为背后的解释,并且有人指出我对功能sum的解释中的差距。
让我这样改写。如果函数 sum 获取字符串作为参数,它会尝试在数据框中找到同名的列
#### sum function receives string as argument, and finds the column and does the sum
input_df.agg(f.sum("developer")).show(5, False)
+--------------+
|sum(developer)|
+--------------+
|3 |
+--------------+
#### sum function receives string as argument, and finds the column and does the sum. Field type is string so it return null
input_df.agg(f.sum("employee")).show(5, False)
+--------------+
|sum(developer)|
+--------------+
|null |
+--------------+
#### sum function receives string as argument, and does not find the column and throws error
input_df.agg(f.sum("manager")).show(5, False)
Py4JJavaError: An error occurred while calling o839.agg.
: org.apache.spark.sql.AnalysisException: cannot resolve '`manager`' given input columns: [department, employee, knwos_ops, developer];
基于上面的 sn-p,我希望函数 when 返回字符串 developer 和
我希望函数sum 将使用该字符串从该字符串中解析列并进行聚合。
【问题讨论】:
标签: apache-spark pyspark apache-spark-sql