【问题标题】:Convert Row into List(String) in PySpark在 PySpark 中将行转换为列表(字符串)
【发布时间】:2019-07-15 19:47:03
【问题描述】:

我有行元组格式的数据 -

Row(Sentence=u'When, for the first time I realized the meaning of death.')

我想把它转换成这样的字符串格式 -

(u'When, for the first time I realized the meaning of death.')

我试过这样(假设“a”在 Row 元组中有数据)-

b = sc.parallelize(a)
b = b.map(lambda line: tuple([str(x) for x in line]))
print(b.take(4))

但我得到的结果是这样的 -

[('W', 'h', 'e', 'n', ',', ' ', 'f', 'o', 'r', ' ', 't', 'h', 'e', ' ', 'f', 'i', 'r', 's', 't', ' ', 't', 'i', 'm', 'e', ' ', 'I', ' ', 'r', 'e', 'a', 'l', 'i', 'z', 'e', 'd', ' ', 't', 'h', 'e', ' ', 'm', 'e', 'a', 'n', 'i', 'n', 'g', ' ', 'o', 'f', ' ', 'd', 'e', 'a', 't', 'h', '.')]

有人知道我在这里做错了什么吗?

【问题讨论】:

    标签: apache-spark pyspark pyspark-sql


    【解决方案1】:

    下面是代码:

    col = 'your_column_name'
    val = df.select(col).collect()
    val2 = [ ele.__getattr__(col) for ele in val]
    

    【讨论】:

    • 通过以下调整(更清洁)对我有用:val2 = [ ele[col] for ele in val]
    【解决方案2】:

    Row(你为什么还要...)应该是:

    a = Row(Sentence=u'When, for the first time I realized the meaning of death.')
    
    b = sc.parallelize([a])
    

    并用扁平化

    b.map(lambda x: x.Sentence)
    

    b.flatMap(lambda x: x)
    

    虽然sc.parallelize(a) 已经是您需要的格式——因为您传递了Iterable,Spark 将遍历Row 中的所有字段以创建RDD

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 2021-04-14
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2023-03-06
      相关资源
      最近更新 更多