Uso de spark withColumn (notas)

 Índice

        Prefácio:

         Sintaxe e uso de spark withColumn:

        Prepare a demonstração dos dados de origem: 

        Código de exemplo completo:


Prefácio:

withColumn(): é uma das funções utilizadas para operações do DataFrame no Apache Spark. Sua função é adicionar ou substituir colunas no DataFrame, ou converter e atualizar colunas existentes, etc.

 Sintaxe e uso de spark withColumn:

1. Adicione uma nova coluna (use withColumn para Dataframe)
2. Altere uma coluna existente
3. Derive uma coluna existente em uma nova coluna
4. Altere o tipo de dados (você pode realizar a conversão de tipo enquanto altera a coluna)
5. Renomeie a coluna name (Você precisa usar withColumnRenamed de DataFrame)
6. Exclua uma coluna (use drop)

Prepare os dados de origem para demonstração: 

import org.apache.spark.SparkConf
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.sql.functions.{col, lit, rand, round}

object text {
  def main(args: Array[String]): Unit = {
    //新建spark
    val spark = new SparkConf().setMaster("local[*]").setAppName("text")
    val sc = SparkSession.builder().config(spark).getOrCreate()
    //准备源数据
    val tuples = Seq(("小白", 19, "江西"),
      ("小红", 20, "安徽"),
      ("小兰", 21, "河北"))
    val frame = sc.createDataFrame(tuples).toDF("name","age","address")
    frame.show()

A saída é:

+------+------+-----+
|nome |idade |endereço|
+------+-------+-- ------+
|Xiaobai | 19 | Jiangxi|
|Xiaohong | 20 | Anhui|
|Xiaolan | 21 | Hebei|
+-------+-------+-- --- --+ 

1. Adicione novas colunas

//语法
 withColumn(colName : String, col : Column) : DataFrame

exemplo:

//1. 用withColumn为dataframe 添加新列
val seq = Seq("小新", 22, "北京")
val frame1 : DataFrame= frame.withColumn("new",round(rand()*100,1) )
frame1.show()   //打印

A saída é:

+------+-----+-------+---------+
|nome|idade|endereço| novo|
+------+- -----+-------+-------+
|Xiaobai|19|Jiangxi|27,7||
Xiaohong|20|Anhui|98,2||
Xiaolan| 21|Hebei| 51,0 |
+ ------+------+-------+-------+

2. Altere colunas existentes
 

//2. 改变现有列
val frame2: DataFrame = frame.withColumn("age", col("age") - 5)
    frame2.show()  // 打印

 A saída é:

+------+------+-------+
|nome|idade|endereço|
+-------+------+---- --+
|Xiaobai | 14| Jiangxi|
|Xiaohong| 15| Anhui|
|Xiaolan | 16| Hebei|
+------+------+-------+

3. Derive novas colunas de colunas existentes
 

    //3.将现有列派生出新列
val frame3 : DataFrame= frame.withColumn("newCol", col("age")*10)
    frame3.show()

A saída é:

+------+--------+--------+--------+
|nome|idade|endereço|novaCol|
+----- --+-------+-------+--------+
|Xiaobai | 19 | Jiangxi| 190|
|Xiaohong | 20 | Anhui| 200|
| Xiaolan| 21 | Hebei| 210|
+--------+------+-------+-------+

4. Altere o tipo de dados (você pode realizar a conversão de tipo enquanto altera a coluna)
 

//4.更改数据类型(可以在改变该列的同时进行类型转换)
val frame4 : DataFrame = frame.withColumn("age", col("age").cast("float"))
    frame4.show

 A saída é:

+-------+-------+-------+
|nome | idade | endereço|
+-------+-------+- ------+
|Xiaobai |19,0 | Jiangxi|
|Xiaohong |20,0 | Anhui|
|Xiaolan |21,0 | Hebei|
+-------+-------+-- --- --+

5. Renomeie o nome da coluna (é necessário usar withColumnRenamed do DataFrame)
 

    // 5.重命名列名(需要使用DataFrame的withColumnRenamed)
    val frame5: DataFrame = frame.withColumnRenamed("address", "省份")
    frame5.show()

A saída é:

+------+------+------+
|nome|idade|província|
+------+------+----+
| Xiaobai| 19 |Jiangxi|
|Xiaohong| 20 |Anhui|
|Xiaolan| 21 |Hebei|
+------+-----+------+

6. Exclua uma coluna (use drop)
 

    // 6.   删除一个列 (使用drop)
    val frame6: DataFrame = frame.drop("age")
    frame6.show

A saída é:

|nome|endereço|
+-------+-------+
|Xiaobai | Jiangxi|
|Xiaohong | Anhui|
|Xiaolan | Hebei|
+-------+- --- ---+


Código de exemplo completo:



import org.apache.spark.SparkConf
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.sql.functions.{col, lit, rand, round}

object text {
  def main(args: Array[String]): Unit = {
    //新建spark
    val spark = new SparkConf().setMaster("local[*]").setAppName("text")
    val sc = SparkSession.builder().config(spark).getOrCreate()
    //准备源数据
    val tuples = Seq(("小白", 19, "江西"),
      ("小红", 20, "安徽"),
      ("小兰", 21, "河北"))
    val frame = sc.createDataFrame(tuples).toDF("name","age","address")
    frame.show()

//1. 用withColumn为dataframe 添加新列
    val seq = Seq("小新", 22, "北京")
    val frame1 : DataFrame= frame.withColumn("new",round(rand()*100,1) )
    frame1.show()

//2. 改变现有列
val frame2: DataFrame = frame.withColumn("age", col("age") - 5)
    frame2.show()  // 打印

//3.将现有列派生出新列
    var a = "省"
val frame3 : DataFrame= frame.withColumn("newCol", col("age")*10)
    frame3.show()

//4.更改数据类型(可以在改变该列的同时进行类型转换)
val frame4 : DataFrame = frame.withColumn("age", col("age").cast("float"))
    frame4.show

    // 5.重命名列名(需要使用DataFrame的withColumnRenamed)
    val frame5: DataFrame = frame.withColumnRenamed("address", "省份")
    frame5.show()

    // 6.   删除一个列 (使用drop)
    val frame6: DataFrame = frame.drop("age")
    frame6.show()
  }
}

Acho que você gosta

Origin blog.csdn.net/m0_69097184/article/details/132856473
Recomendado
Clasificación