在 PySpark 中将行转换为列表(字符串)

Convert Row into List(String) in PySpark

我有行元组格式的数据 -

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 tupple 中有数据)-

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', '.')]

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

单人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

代码如下:

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