如何根据键值将转换为数组的数据框添加为另一个数据框的元素
How can I add a dataframe converted to an array as an element of another dataframe based on a key value
我一直在尝试根据键值将数据帧的结果作为新数组字段添加到另一个数据帧中。
例如,我有这个数据框,我们称它为df1
:
root
|-- DF_KEY: integer (nullable = false)
|-- DF_DESC: string (nullable = false)
+------------+--------------------+
|DF_KEY | DF_DESC |
+------------+--------------------+
| 10000|String Desc A |
| 10000|String Desc B |
还有另一个数据框df2
:
root
|-- DF_KEY: integer (nullable = false)
|-- COL_A: decimal(20,0) (nullable = true)
|-- COL_B: decimal(20,0) (nullable = true)
|-- COL_C: string (nullable = false)
我想将两个数据帧与 df1
的结果合并为一个新数组 ARRAY_OF_DF_DESC
,这将生成具有以下架构的数据帧 (newDF
)。
root
|-- DF_KEY: integer (nullable = false)
|-- COL_A: decimal(20,0) (nullable = true)
|-- COL_B: decimal(20,0) (nullable = true)
|-- COL_C: string (nullable = false)
|-- ARRAY_OF_DF_DESC : array (nullable = false)
| |-- element: string (containsNull = false)
我试过加入:
val otherRefsArray = df1.select($"DF_KEY", array(df1.columns.map(col): _*) as "ARRAY_OF_DF_DESC ")
val newDF = df2.join(otherRefsArray, "DF_KEY")
但是这个连接只为每个 df1
行添加了一个 WrappedArray
到 newDf
数据框。它 returns 每个 DF_DESC
.
的重复记录
如果可能,我想传递一个 WrappedArray
,其中包含与该行的 DF_KEY
关联的所有 DF_DESC
。有谁知道如何用 scala 做到这一点?
您可以使用 groupBy()
并为每个键收集一个列表。
val otherRefsArray = df1.groupBy($"DF_KEY")
.agg(collect_list($"DF_DESC").as("ARRAY_OF_DF_DESC"))
之后,和之前一样使用join
我一直在尝试根据键值将数据帧的结果作为新数组字段添加到另一个数据帧中。
例如,我有这个数据框,我们称它为df1
:
root
|-- DF_KEY: integer (nullable = false)
|-- DF_DESC: string (nullable = false)
+------------+--------------------+
|DF_KEY | DF_DESC |
+------------+--------------------+
| 10000|String Desc A |
| 10000|String Desc B |
还有另一个数据框df2
:
root
|-- DF_KEY: integer (nullable = false)
|-- COL_A: decimal(20,0) (nullable = true)
|-- COL_B: decimal(20,0) (nullable = true)
|-- COL_C: string (nullable = false)
我想将两个数据帧与 df1
的结果合并为一个新数组 ARRAY_OF_DF_DESC
,这将生成具有以下架构的数据帧 (newDF
)。
root
|-- DF_KEY: integer (nullable = false)
|-- COL_A: decimal(20,0) (nullable = true)
|-- COL_B: decimal(20,0) (nullable = true)
|-- COL_C: string (nullable = false)
|-- ARRAY_OF_DF_DESC : array (nullable = false)
| |-- element: string (containsNull = false)
我试过加入:
val otherRefsArray = df1.select($"DF_KEY", array(df1.columns.map(col): _*) as "ARRAY_OF_DF_DESC ")
val newDF = df2.join(otherRefsArray, "DF_KEY")
但是这个连接只为每个 df1
行添加了一个 WrappedArray
到 newDf
数据框。它 returns 每个 DF_DESC
.
如果可能,我想传递一个 WrappedArray
,其中包含与该行的 DF_KEY
关联的所有 DF_DESC
。有谁知道如何用 scala 做到这一点?
您可以使用 groupBy()
并为每个键收集一个列表。
val otherRefsArray = df1.groupBy($"DF_KEY")
.agg(collect_list($"DF_DESC").as("ARRAY_OF_DF_DESC"))
之后,和之前一样使用join