简体   繁体   中英

split a array columns into rows pyspark

I have a DataFrame similar to following:

new_df = spark.createDataFrame([
    ([['hello', 'productcode'], ['red','color']], 7),
    ([['hi', 'productcode'], ['blue', 'color']], 8),
    ([['hoi', 'productcode'], ['black','color']], 7)
], ["items", "frequency"])
new_df.show(3, False)

# +------------------------------------------------------------+---------+
# |items                                                       |frequency|
# +------------------------------------------------------------+---------+
# |[WrappedArray(hello, productcode), WrappedArray(red, color)]|7        |
# |[WrappedArray(hi, productcode), WrappedArray(blue, color)]  |8        |
# |[WrappedArray(hoi, productcode), WrappedArray(black, color)]|7        |
# +------------------------------------------------------------+---------+

I need to generate a new DataFrame similar to following:

# +-------------------------------------------
# |productcode     | color         |frequency|
# +-------------------------------------------
# |hello           | red          |       7  |
# |hi              | blue         |       8  |
# |hoi             | black        |       7  |
# +--------------------------------------------

You can convert items to map :

from pyspark.sql.functions import *
from operator import itemgetter

@udf("map<string, string>")
def as_map(vks):
    return {k: v for v, k in vks}

remapped = new_df.select("frequency", as_map("items").alias("items"))

Collect the keys:

keys = remapped.select("items").rdd \
   .flatMap(lambda x: x[0].keys()).distinct().collect()

And select:

remapped.select([col("items")[key] for key in keys] + ["frequency"]) 

+------------+------------------+---------+
|items[color]|items[productcode]|frequency|
+------------+------------------+---------+
|         red|             hello|        7|
|        blue|                hi|        8|
|       black|               hoi|        7|
+------------+------------------+---------+

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