简体   繁体   中英

Spark, how to get the pivoted column names from dataframe?

I pivot a column and it generates multiple new columns.

I'd like to get those columns and pack it under a field.

Below code gives me the result I want.
But I'm manually selecting col("search"), col("main"), col("theme") , I wonder if there's a way of dynamically selecting all those columns (pivoted columns may I say?))

 # I'm going to pivot on the 2nd column
 mylist = [
     [1, 'search', 3, 1],
     [1, 'search', 3, 2],
     [1, 'main', 5, 3],
     [1, 'main', 6, 4],

     [2, 'search', 4, 10],
     [2, 'search', 4, 11],
     [2, 'main', 6, 12],
     [2, 'main', 6, 13],
     [2, 'theme', 6, 14],

     [3, 'search', 4, 5],
     [3, 'main', 6, 6],
     [3, 'main', 6, 7],
     [3, 'theme', 6, 8],
 ]

 df = pd.DataFrame(mylist, columns=['id', 'origin', 'time', 'screen_index'])

 mylist = df.to_dict('records')
 spark_session = get_spark_session()

 df = spark_session.createDataFrame(Row(**x) for x in mylist)

 df_wanted = df.groupBy("id").pivot('origin').agg(
     struct(count(lit(1)).alias('count'), avg("time").alias('avg_time'))
 ).withColumn(
     #### here I'm manually selecting columns, but want to grab them dynamically because I don't know beforehand what they gonna be.
     "origin_info", struct(col("search"), col("main"), col("theme")) 
 ).select("id", "origin_info")


 df_wanted.printSchema()
 root
  |-- id: long (nullable = true)
  |-- origin_info: struct (nullable = false)
  |    |-- search: struct (nullable = false)
  |    |    |-- count: long (nullable = false)
  |    |    |-- avg_time: double (nullable = true)
  |    |-- main: struct (nullable = false)
  |    |    |-- count: long (nullable = false)
  |    |    |-- avg_time: double (nullable = true)
  |    |-- theme: struct (nullable = false)
  |    |    |-- count: long (nullable = false)
  |    |    |-- avg_time: double (nullable = true)

Actually I think I figured it out.
Although I have no idea it's performance..

I got the hints from https://stackoverflow.com/a/41011195/433570

names = df_wanted.schema.names.copy()
names.remove("id")

columns = [col(name) for name in names]


df_wanted = df_wanted.withColumn(
    "origin_info", struct(*columns)
).select("id", "origin_info")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM