【发布时间】:2018-06-12 05:31:20
【问题描述】:
这是我的 mongodb 集合架构的一部分:
|-- variables: struct (nullable = true)
| |-- actives: struct (nullable = true)
| | |-- data: struct (nullable = true)
| | | |-- 0: struct (nullable = true)
| | | | |--active: integer (nullable = true)
| | | | |-- inactive: integer (nullable = true)
我已获取集合并将其存储在 Spark 数据框中,现在正尝试提取 variables 列中最里面的值。
df_temp = df1.select(df1.variables.actives.data)
这工作得很好,我能够得到 data 结构的内部结构。
+----------------------+
|variables.actives.data|
+----------------------+
| [[1,32,0.516165...|
| [[1,30,1.173139...|
| [[4,18,0.160088...|
但是,一旦我尝试更进一步:
df_temp = df1.select(df1.variables.actives.data.0.active)
我收到一个无效语法错误。
df_temp = df1.select(df1.variables.actives.data.0.active)
^
SyntaxError: 无效语法
问题在于我的内部字段键名是数字,我找不到内部字段键名是数字的示例。
实现从数据框中检索最里面的值(active 和 inactive)目标的最佳方法是什么?
【问题讨论】:
-
为什么不直接使用
df1.select("variables.actives.data.0.active")? -
投票重新打开,因为这个问题指的是 pyspark(在 Python 中),而不是 Spark(在 Scala 中)
-
由于问题已关闭,我将添加我的答案作为评论:您可以使用
element_at('array_col_name', one_based_index).alias('new_col_name)从数组中选择列,使用col('struct_col_name.struct_field_name').alias('new_col_name')从结构中选择列,并将所有这些新列放入 @ 987654328@ 例如result_df = df.select(*array_of_new_cols)
标签: apache-spark pyspark spark-dataframe