【问题标题】:Parsing a string into a Dataframe将字符串解析为数据框
【发布时间】:2019-10-31 23:02:50
【问题描述】:

我有以下数据

100///t1001///t2///t0.119///t2342342342///tHi\nthere!///n103///t1002///t2///t0.119///t2342342342///tHello
there!
1010///t10077///t2///t0.119///t2342342342///tHi\nthere!///n1044///t1003///t2///t0.119///t2342342342///tHello there!

在一个文件中,我有多行上述格式的数据。每行由///n///t 分隔。对于每一行,有四个由///n 分隔的记录。在每条记录中,有四列由///t 分隔。现在,我需要将其解析为 Dataframe。所以基本上针对以上两行;因为每行有 2 条记录,有 6 列; Dataframe 中应该有 12 条记录。每条记录都遵循相同的格式。

我尝试使用 split 和 amp 的组合来解析它,但没有得到正确的输出

【问题讨论】:

    标签: arrays scala dataframe


    【解决方案1】:

    您可以使用字符串转换来处理它,例如:

    // Sample of input data
    val str1 = "100///t1001///t2///t0.119///t2342342342///tHi\nthere!///n103///t1002///t2///t0.119///t2342342342///tHello there!"
    val str2 = "1010///t10077///t2///t0.119///t2342342342///tHi\nthere!///n1044///t1003///t2///t0.119///t2342342342///tHello there!"
    
    val df = Seq(str1, str2).toDF
    
    // Process:
        val output = df.as[String].flatMap(row=>{
      val fields = row.split("///n").map(record=>{
        val fields = record.split("///t").toList
        (fields(0), fields(1), fields(2), fields(3), fields(4), fields(5))
      }).toList
      fields
    }).toDF("column_1", "column_2", "column_3", "column_4", "column_5", "column_6")
    

    结果:

    +--------+--------+--------+--------+----------+------------+
    |column_1|column_2|column_3|column_4|  column_5|    column_6|
    +--------+--------+--------+--------+----------+------------+
    |     100|    1001|       2|   0.119|2342342342|   Hi       |
    |                                              |there!      |
    |     103|    1002|       2|   0.119|2342342342|Hello there!|
    |    1010|   10077|       2|   0.119|2342342342|   Hi       |
    |                                              |      there!|
    |    1044|    1003|       2|   0.119|2342342342|Hello there!|
    +--------+--------+--------+--------+----------+------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-07
      • 2018-05-17
      • 2022-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多