簡體   English   中英

將CSV數據加載到Dataframe中,然后使用Apache Spark(Java)轉換為Array

[英]Load CSV data in to Dataframe and convert to Array using Apache Spark (Java)

我有一個包含以下數據的CSV文件:

1,2,5  
2,4  
2,3 

我想將它們加載到具有數組字符串模式的Dataframe中

輸出應如下所示。

[1, 2, 5]  
[2, 4]  
[2, 3] 

這已在此處使用scala進行了解答: Spark:將字符串列轉換為數組

我想讓它在Java中實現。
請幫忙

以下是Java中的示例代碼。 您需要使用spark.read().text(String path)方法讀取文件,然后調用split函數。

import static org.apache.spark.sql.functions.split;

public class SparkSample {
    public static void main(String[] args) {
        SparkSession spark = SparkSession
                .builder()
                .appName("SparkSample")
                .master("local[*]")
                .getOrCreate();
        //Read file
        Dataset<Row> ds = spark.read().text("c://tmp//sample.csv").toDF("value");
        ds.show(false);     
        Dataset<Row> ds1 = ds.select(split(ds.col("value"), ",")).toDF("new_value");
        ds1.show(false);
        ds1.printSchema();
    }
}

您可以使用VectorAssembler類將其創建為要素數組,這對於管道特別有用:

val assembler = new VectorAssembler()
  .setInputCols(Array("city", "status", "vendor"))
  .setOutputCol("features")

https://spark.apache.org/docs/2.2.0/ml-features.html#vectorassembler

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM