所以,首先我有一些像这样的输入:

A:<phone1,phone2>,<location1>,<email1>
B:<phone1>,<location2>,<email1,email2>

我想使用Pyspark.rdd.map()函数在行中每次循环,并将它们变成键-值对,如下所示:

phone1: A:<phone1,phone2>,<location1>,<email1>
phone1: B:<phone1>,<location2>,<email1,email2>
phone2: A:<phone1,phone2>,<location1>,<email1>
location1: A:<phone1,phone2>,<location1>,<email1>
location2: B:<phone1>,<location2>,<email1,email2>
email1: A:<phone1,phone2>,<location1>,<email1>
email1: B:<phone1>,<location2>,<email1,email2>
email2: B:<phone1>,<location2>,<email1,email2>

在之前的尝试中,我尝试在map函数内部的lambda函数上添加一个循环,但是它不支持该循环。 还有其他办法吗?

===============>>#1 票数:0

    scala> val rdd =  sc.parallelize(Seq("A:<phone1,phone2>,<location1>,<email1>", "B:<phone1>,<location2>,<email1,email2>"))

    scala> rdd.foreach(println)
    A:<phone1,phone2>,<location1>,<email1>
    B:<phone1>,<location2>,<email1,email2>

    scala> case class dataclass(c0:String, c1:String)

    scala> val df = rdd.map(x => x.split(":")).map(y => dataclass(y(0), y(1))).toDF

    scala> df.show(false)
    +---+------------------------------------+
    |c0 |c1                                  |
    +---+------------------------------------+
    |A  |<phone1,phone2>,<location1>,<email1>|
    |B  |<phone1>,<location2>,<email1,email2>|
    +---+------------------------------------+


    scala> val df1 = df.withColumn("tempCol",regexp_replace(regexp_replace(col("c1"), "<", ""),">", ""))
                       .withColumn("tempCol", explode(split(col("tempCol"), ",")))
                       .withColumn("out", concat(col("tempCol"), lit(":"), col("c0"), lit(":"), col("c1")))
                       .drop("c0", "c1", "tempCol")

    scala> df1.show(false)
    +------------------------------------------------+
    |out                                             |
    +------------------------------------------------+
    |phone1:A:<phone1,phone2>,<location1>,<email1>   |
    |phone2:A:<phone1,phone2>,<location1>,<email1>   |
    |location1:A:<phone1,phone2>,<location1>,<email1>|
    |email1:A:<phone1,phone2>,<location1>,<email1>   |
    |phone1:B:<phone1>,<location2>,<email1,email2>   |
    |location2:B:<phone1>,<location2>,<email1,email2>|
    |email1:B:<phone1>,<location2>,<email1,email2>   |
    |email2:B:<phone1>,<location2>,<email1,email2>   |
    +------------------------------------------------+

    scala> val rdd2 = df1.rdd.map(_(0))
    scala> rdd2.foreach(println)
    phone1:A:<phone1,phone2>,<location1>,<email1>
    phone2:A:<phone1,phone2>,<location1>,<email1>
    location1:A:<phone1,phone2>,<location1>,<email1>
    email1:A:<phone1,phone2>,<location1>,<email1>
    phone1:B:<phone1>,<location2>,<email1,email2>
    location2:B:<phone1>,<location2>,<email1,email2>
    email1:B:<phone1>,<location2>,<email1,email2>
    email2:B:<phone1>,<location2>,<email1,email2>

  ask by GDJi translate from so

未解决问题?本站智能推荐:

关注微信公众号