【问题标题】:Split pyspark dataframe column and limit the splits拆分 pyspark 数据框列并限制拆分
【发布时间】:2021-11-25 11:19:10
【问题描述】:

我有以下 spark 数据框。

Column_1
Physics=99;name=Xxxx;age=15
Physics=97;chemistry=85;name=yyyy;age=14
Physics=97;chemistry=85;maths=65;name=zzzz;age=14

我必须将上面的数据框列拆分为多个列,如下所示。

column_1                         name   age
Physics=99                       Xxxx         15
Physics=97;chemistry=85          yyyy           14
Physics=97;chemistry=85;maths=65 zzzz      14

我尝试使用分隔符进行拆分;和限制。但它也将主题分成不同的列。姓名和年龄合并到一个列中。我要求将所有科目放在一列中,仅将姓名和年龄放在单独的列中。

是否有可能在 Pyspark 中实现这一点。

【问题讨论】:

  • 作为数组还是字符串?
  • 我需要它作为字符串

标签: apache-spark pyspark


【解决方案1】:

您可以使用替换技巧来拆分列。

df = spark.createDataFrame([('Physics=99;name=Xxxx;age=15'),('Physics=97;chemistry=85;name=yyyy;age=14'),('Physics=97;chemistry=85;maths=65;name=zzzz;age=14')], 'string').toDF('c1')

df.withColumn('c1', f.regexp_replace('c1', ';name', ',name')) \
  .withColumn('c1', f.regexp_replace('c1', ';age', ',age')) \
  .withColumn('c1', f.split('c1', ',')) \
  .select(
    f.col('c1')[0].alias('stat'),
    f.col('c1')[1].alias('name'),
    f.col('c1')[2].alias('age')) \
  .show(truncate=False)

+--------------------------------+---------+------+
|stat                            |name     |age   |
+--------------------------------+---------+------+
|Physics=99                      |name=Xxxx|age=15|
|Physics=97;chemistry=85         |name=yyyy|age=14|
|Physics=97;chemistry=85;maths=65|name=zzzz|age=14|
+--------------------------------+---------+------+

【讨论】:

    【解决方案2】:

    您可以这样做以使用正则表达式提取名称:

    import pyspark.sql.functions as F
    df = spark.createDataFrame([("Physics=99;name=Xxxx;age=15",), ("Physics=97;chemistry=85;name=yyyy;age=14",),("Physics=97;chemistry=85;maths=65;name=zzzz;age=14",)], ["Column1"])
    new_df = df.withColumn("name", F.regexp_extract('Column1', r'name=(\w+)', 1).alias('name'))
    new_df.show()
    

    输出:

    +--------------------+----+
    |             Column1|name|
    +--------------------+----+
    |Physics=99;name=X...|Xxxx|
    |Physics=97;chemis...|yyyy|
    |Physics=97;chemis...|zzzz|
    +--------------------+----+
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多