当前位置: 代码迷 >> java >> Java-Spark:如何获取数据集 在循环中迭代时的列值,并在when()。otherwise()中使用它?
  详细解决方案

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

热度:19   发布时间:2023-08-02 11:03:52.0

我有一个Dataset<Row> ,其列的值为"null" (空的书面文本)。
我正在尝试将“空”文本替换为文本: \\ N。
为此,我使用一种逻辑,即添加一个新列,并在名称后加上“ _nulled”,例如,列abc变为abc_nulled,并且如果当前值是text null ,则该新列的值为“ \\ N”,否则该值保持原样。
为此,我使用了withColumn(<new name>, when(col.equalTo("null"), "\\\\N").otherwise(<existing_value>)) 如何获得此<existing_value>
当我传递otherwise(ds.col(col_nm))它不起作用,可能是因为它期望在otherwise(ds.col(col_nm)) otherwise()找到一个String并找到一个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);

我通过在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
  相关解决方案