【问题标题】:Pyspark dataframe explode string columnPyspark 数据框爆炸字符串列
【发布时间】:2022-06-14 23:45:35
【问题描述】:

我正在寻找一种有效的方法来将 pyspark 数据框 df_input 中的行分解为列。我不明白'@{name...}' 的格式,也不知道从哪里开始解码。感谢您的帮助!

df_input = sqlContext.createDataFrame(
    [
        (1, '@{name= Hans; age= 45}'), 
        (2, '@{name= Jeff; age= 15}'), 
        (3, '@{name= Elona; age= 23}')
    ], 
    ('id', 'firstCol')
      )
   

预期结果:

+---+-----+---+
| id| name|age|
+---+-----+---+
|  1| Hans| 45|
|  2| Jeff| 15|
|  3|Elona| 23|
+---+-----+---+

【问题讨论】:

  • 当您在真实数据帧上使用df.printSchema() 时,您会看到哪些数据类型?
  • 数据类型为字符串

标签: python pyspark


【解决方案1】:
from  pyspark.sql.functions import regexp_extract

df_input.select( 
 df_input.id, #id
 regexp_extract( #use regex
  df_input.firstCol, #on firstCol
  '\s(.*);', #find a space character then capture a (group of text) until you find a ';'
  1 # use capture group 1 as text
 ).alias("name"), 
 regexp_extract(
  df_input.firstCol, 
  '\s.*\s(.*)}', #find the second space then capture a (group  of text) until you find a '}'
  1 # use capture group 1 as text
 ).alias("age") 
).show()
+---+-----+---+
| id| name|age|
+---+-----+---+
|  1| Hans| 45|
|  2| Jeff| 15|
|  3|Elona| 23|
+---+-----+---+

【讨论】:

    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2018-11-13
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多