当列为可选时如何从数据框中选择

时间:2018-07-02 21:53:33

标签: scala apache-spark dataframe apache-spark-sql

我有一个Spark(标量)数据帧,其中一些数据帧列是可选的,也就是说,有时它们不存在。是否有一种非常简单的方法来修改我的df.select语句,以使spark不在乎该列可能不存在?

例如,现在我有:df.select(Seq(col("col1"), col("optionalCol"), col("col2")))

我希望会有某种“可选”名称。

2 个答案:

答案 0 :(得分:0)

来自Spark docs

您可以使用以下方法检查该列是否存在

// returns true if the column exists else returns false
if(df.columns.contains("optional_col")) {
         df.select(Seq(col("col1"), col("optionalCol"), col("col2")))
}    
else {
        df.select(Seq(col("col1"),  col("col2")))
}

答案 1 :(得分:0)

您可以获取可能需要关注的列,然后过滤掉数据框中不存在的列。

 $FFMpeg = FFMpeg\FFMpeg::create([
        'ffmpeg.binaries'  => 'C:\xampp\htdocs\lary\blog\ffmpeg\bin', // the path to the FFMpeg binary
        'ffprobe.binaries' => 'C:\xampp\htdocs\lary\blog\ffmpeg\bin', // the path to the FFProbe binary
        'timeout'          => 3600, // the timeout for the underlying process
        'ffmpeg.threads'   => 12,   // the number of threads that FFMpeg should use
    ]);