programing

스파크 스칼라에서 데이터 프레임의 열 이름 바꾸기

telecom 2023. 9. 17. 12:08
반응형

스파크 스칼라에서 데이터 프레임의 열 이름 바꾸기

의 모든 머리글/열 이름을 변환하려고 합니다.DataFrameSpark-Scala. 현재 저는 하나의 열 이름만을 대체하는 다음 코드를 생각해냅니다.

for( i <- 0 to origCols.length - 1) {
  df.withColumnRenamed(
    df.columns(i), 
    df.columns(i).toLowerCase
  );
}

구조물이 평평한 경우:

val df = Seq((1L, "a", "foo", 3.0)).toDF
df.printSchema
// root
//  |-- _1: long (nullable = false)
//  |-- _2: string (nullable = true)
//  |-- _3: string (nullable = true)
//  |-- _4: double (nullable = false)

당신이 할 수 있는 가장 간단한 것은 사용하는 것입니다.toDF방법:

val newNames = Seq("id", "x1", "x2", "x3")
val dfRenamed = df.toDF(newNames: _*)

dfRenamed.printSchema
// root
// |-- id: long (nullable = false)
// |-- x1: string (nullable = true)
// |-- x2: string (nullable = true)
// |-- x3: double (nullable = false)

개별 열 이름을 변경하려면 다음 중 하나를 사용할 수 있습니다.select와 함께alias:

df.select($"_1".alias("x1"))

여러 열에 쉽게 일반화할 수 있습니다.

val lookup = Map("_1" -> "foo", "_3" -> "bar")

df.select(df.columns.map(c => col(c).as(lookup.getOrElse(c, c))): _*)

아니면withColumnRenamed:

df.withColumnRenamed("_1", "x1")

와 함께 사용되는foldLeft여러 열의 이름을 변경하려면:

lookup.foldLeft(df)((acc, ca) => acc.withColumnRenamed(ca._1, ca._2))

중첩 구조() 포함structs) 전체 구조를 선택하여 이름을 변경하는 것이 한 가지 가능한 방법입니다.

val nested = spark.read.json(sc.parallelize(Seq(
    """{"foobar": {"foo": {"bar": {"first": 1.0, "second": 2.0}}}, "id": 1}"""
)))

nested.printSchema
// root
//  |-- foobar: struct (nullable = true)
//  |    |-- foo: struct (nullable = true)
//  |    |    |-- bar: struct (nullable = true)
//  |    |    |    |-- first: double (nullable = true)
//  |    |    |    |-- second: double (nullable = true)
//  |-- id: long (nullable = true)

@transient val foobarRenamed = struct(
  struct(
    struct(
      $"foobar.foo.bar.first".as("x"), $"foobar.foo.bar.first".as("y")
    ).alias("point")
  ).alias("location")
).alias("record")

nested.select(foobarRenamed, $"id").printSchema
// root
//  |-- record: struct (nullable = false)
//  |    |-- location: struct (nullable = false)
//  |    |    |-- point: struct (nullable = false)
//  |    |    |    |-- x: double (nullable = true)
//  |    |    |    |-- y: double (nullable = true)
//  |-- id: long (nullable = true)

영향을 미칠 수 있음을 유의하십시오.nullability메타데이터.캐스팅을 통해 이름을 변경하는 것도 가능합니다.

nested.select($"foobar".cast(
  "struct<location:struct<point:struct<x:double,y:double>>>"
).alias("record")).printSchema

// root
//  |-- record: struct (nullable = true)
//  |    |-- location: struct (nullable = true)
//  |    |    |-- point: struct (nullable = true)
//  |    |    |    |-- x: double (nullable = true)
//  |    |    |    |-- y: double (nullable = true)

또는:

import org.apache.spark.sql.types._

nested.select($"foobar".cast(
  StructType(Seq(
    StructField("location", StructType(Seq(
      StructField("point", StructType(Seq(
        StructField("x", DoubleType), StructField("y", DoubleType)))))))))
).alias("record")).printSchema

// root
//  |-- record: struct (nullable = true)
//  |    |-- location: struct (nullable = true)
//  |    |    |-- point: struct (nullable = true)
//  |    |    |    |-- x: double (nullable = true)
//  |    |    |    |-- y: double (nullable = true)

PySpark 버전에 관심이 있으신 분들(실제로는 Scala에서도 동일함 - 아래 코멘트 참조):

    merchants_df_renamed = merchants_df.toDF(
        'merchant_id', 'category', 'subcategory', 'merchant')

    merchants_df_renamed.printSchema()

결과:

뿌리
|-- merchant_id: 정수(선택 가능 = true)
|-- 범주: 문자열(선택할 수 없음 = true)
|-- 하위 범주: 문자열(선택할 수 없음 = true)
|-- 머천트: 문자열(선택할 수 없음 = true

def aliasAllColumns(t: DataFrame, p: String = "", s: String = ""): DataFrame =
{
  t.select( t.columns.map { c => t.col(c).as( p + c + s) } : _* )
}

명확하지 않은 경우 현재 열 이름 각각에 접두사와 접미사를 추가합니다.이름이 같은 열이 하나 이상 있는 두 개의 테이블이 있는 경우 이 테이블에 결합하려고 하지만 결과 테이블의 열을 명확하게 구분할 수 있는 경우 유용합니다."일반" SQL에서도 이와 유사한 방법이 있다면 좋을 것입니다.

데이터 프레임 df에 3개의 열 id1, name1, price1이 있다고 가정하고 id2, name2, price2로 이름을 바꾸려고 합니다.

val list = List("id2", "name2", "price2")
import spark.implicits._
val df2 = df.toDF(list:_*)
df2.columns.foreach(println)

저는 이 방법이 많은 경우에 유용하다고 생각했습니다.

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

tow table join 결합된 키의 이름을 변경하지 않음

// method 1: create a new DF
day1 = day1.toDF(day1.columns.map(x => if (x.equals(key)) x else s"${x}_d1"): _*)

// method 2: use withColumnRenamed
for ((x, y) <- day1.columns.filter(!_.equals(key)).map(x => (x, s"${x}_d1"))) {
    day1 = day1.withColumnRenamed(x, y)
}

효과가 있습니다!

언급URL : https://stackoverflow.com/questions/35592917/renaming-column-names-of-a-dataframe-in-spark-scala

반응형