我有一个包含以下数据的DataFrame:
num_cta | n_lines
110000000000| 2
110100000000| 3
110200000000| 1
根据这些信息,我需要创建一个具有不同行数的新DF,具体取决于 n_lines 列上的值。
例如,对于我的DF的第一行( 110000000000 ), n_lines 列的值为 2 。结果必须类似于以下内容:
num_cta
110000000000
110000000000
对于我展示的所有Dataframe示例,get的结果必须是这样的:
num_cta
110000000000
110000000000
110100000000
110100000000
110100000000
110200000000
有办法吗?并乘以 n 行,具体取决于列值的值?
问候。
答案 0 :(得分:1)
这样做没有搁置的方式。但是,您可以尝试遍历数据帧并返回num_cta列表,其中元素的数量等于相应的n_lines。
像
这样的东西 import spark.implicits._
case class (num_cta:String) // output dataframe schema
case class (num_cta:String, n_lines:Integer) // input dataframe 'df' schema
val result = df.flatmap(x => {
List.fill(x.n_lines)(x.num_cta)
}).toDF
答案 1 :(得分:1)
一种方法是将n_lines
扩展为包含UDF和explode
的数组:
val df = Seq(
("110000000000", 2),
("110100000000", 3),
("110200000000", 1)
)toDF("num_cta", "n_lines")
def fillArr = udf(
(n: Int) => Array.fill(n)(1)
)
val df2 = df.withColumn("arr", fillArr($"n_lines")).
withColumn("a", explode($"arr")).
select($"num_cta")
df2.show
+------------+
| num_cta|
+------------+
|110000000000|
|110000000000|
|110100000000|
|110100000000|
|110100000000|
|110200000000|
+------------+