Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何提取具有特定值的列名_Scala_Apache Spark - Fatal编程技术网

Scala 如何提取具有特定值的列名

Scala 如何提取具有特定值的列名,scala,apache-spark,Scala,Apache Spark,我有一个包含列名的列名列表,我迭代一行并检查它是否包含1,然后将该列名附加到列表中。使用zip或其他方法是否更好 private def getNames(row: Row): List[String] = { val listofColumnNames = row.schema.fields.map(_.name).toList val listOfColumnWhichContainOne = ArrayBuffer[String]() listofColumnNames

我有一个包含列名的列名列表,我迭代一行并检查它是否包含1,然后将该列名附加到列表中。使用zip或其他方法是否更好

private def getNames(row: Row): List[String] = {
 val listofColumnNames = row.schema.fields.map(_.name).toList
    val listOfColumnWhichContainOne =  ArrayBuffer[String]()
    listofColumnNames.indices.foreach(index => {
      if(row.getInt(index).equals(1)) {
        listOfColumnWhichContainOne.append(listofColumnNames(index))
      }
    })
    listofColumnNames.toList
}

可以简化吗?

您可以将一个新列添加到现有数据框中,该数据框包含所有列的列表,其中对于该特定行,字段的值为
1

在的列参数中,可以迭代所有其他列并检查所需的值:

val df=Seq((1,2,3)、(4,5,6)、(3,2,1)).toDF(“col1”、“col2”、“col3”)
df.show()
val cols=df.schema.fieldNames//根据需要更改此数组
//如果要从检查中排除列
df.withColumn(“结果”,数组(
科尔斯地图{
c:String=>when(col(c).equalTo(1),c)
}: _*
)).show()
印刷品:

//输入数据
+----+----+----+
|col1 | col2 | col3|
+----+----+----+
|   1|   2|   3|
|   4|   5|   6|
|   3|   1|   1|
+----+----+----+
//结果
+----+----+----+--------------+
|col1 | col2 | col3 |结果|
+----+----+----+--------------+
|1 | 2 | 3 |[col1,,]|
|   4|   5|   6|          [,,]|
|3 | 1 | 1 |[,col2,col3]|
+----+----+----+--------------+

您能发布您的实际模式和预期模式吗??