Java-Spark:如何获取数据集 在循环中迭代时的列值,并在when()中使用它。否则()?

问题描述 投票:0回答:1

我有一个Dataset<Row>列的值为"null"(null书面文字)。 我试图将“null”文本替换为text:\ N. 为此,我使用一个逻辑,我将添加一个名为“_nulled”的新列,例如column abc变为abc_nulled,如果当前值为text null,则此新列将具有值“\ N”,否则值保持不变。 为此,我使用了withColumn(<new name>, when(col.equalTo("null"), "\\N").otherwise(<existing_value>))。我如何获得这个<existing_value>。 当我通过otherwise(ds.col(col_nm))它不起作用,可能是因为它期待在Stringotherwise()并找到Column

我该如何解决这个问题?这是代码:

ArrayList<String> newCols = new ArrayList<String>();
List<String> reqColListCopy = Arrays.asList(reqCols);
Dataset<Row> testingDS = DS.selectExpr(JavaConverters.asScalaIteratorConverter(reqColListCopy.iterator()).asScala().toSeq())

//Creating newCols (ArrayList so that I can add/remove column names.
Iterator itrTmp2 = reqColListCopy.iterator();
while(itrTmp2.hasNext()){
    newCols.add((String)itrTmp2.next());
}

//Creating a List reference for newCols ArrayList. This will be used to get Seq(<columns>).
List<String> newColsList = newCols;

Iterator colListItr = reqColListCopy.iterator();
while(colListItr.hasNext())
{
    String col = colListItr.next().toString();
    testingDS = testingDS.selectExpr(convertListToSeq(newColsList))
            .withColumn(col+"_nulled",  functions.when(testingDS.col(col).equalTo("null"), functions.lit("\\N")).otherwise(testingDS.col(col))) //'otherwise' needs a string parameter
            .drop(testingDS.col(col));

    newCols.add(col+"_nulled");
    newCols.remove(col);
    newColsList = newCols;
}
Dataset<Row> testingDS = DS.selectExpr(JavaConverters.asScalaIteratorConverter(newColsList.iterator()).asScala().toSeq())

testingDS.show(false);
java apache-spark apache-spark-sql apache-spark-dataset
1个回答
0
投票

我通过在lit()中传递列来解决它:

.withColumn(col+"_nulled",  functions.when(testingDS.col(col).equalTo("null"), functions.lit("\\N")).otherwise(functions.lit(testingDS.col(col)))) //'otherwise' needs a string parameter
© www.soinside.com 2019 - 2024. All rights reserved.