Python 星星之火
我想将包含单词列表的数据框转换为每个单词都在自己的行中的数据框 如何在数据帧中的列上进行分解 下面是我的一些尝试的示例,您可以取消注释每一行代码,并在下面的注释中列出错误。我在Python2.7和Spark 1.6.1中使用PySparkPython 星星之火,python,apache-spark,pyspark,apache-spark-sql,Python,Apache Spark,Pyspark,Apache Spark Sql,我想将包含单词列表的数据框转换为每个单词都在自己的行中的数据框 如何在数据帧中的列上进行分解 下面是我的一些尝试的示例,您可以取消注释每一行代码,并在下面的注释中列出错误。我在Python2.7和Spark 1.6.1中使用PySpark from pyspark.sql.functions import split, explode DF = sqlContext.createDataFrame([('cat \n\n elephant rat \n rat cat', )], ['word'
from pyspark.sql.functions import split, explode
DF = sqlContext.createDataFrame([('cat \n\n elephant rat \n rat cat', )], ['word'])
print 'Dataset:'
DF.show()
print '\n\n Trying to do explode: \n'
DFsplit_explode = (
DF
.select(split(DF['word'], ' '))
# .select(explode(DF['word'])) # AnalysisException: u"cannot resolve 'explode(word)' due to data type mismatch: input to function explode should be array or map type, not StringType;"
# .map(explode) # AttributeError: 'PipelinedRDD' object has no attribute 'show'
# .explode() # AttributeError: 'DataFrame' object has no attribute 'explode'
).show()
# Trying without split
print '\n\n Only explode: \n'
DFsplit_explode = (
DF
.select(explode(DF['word'])) # AnalysisException: u"cannot resolve 'explode(word)' due to data type mismatch: input to function explode should be array or map type, not StringType;"
).show()
请注意
分解
和拆分
都是SQL函数。两者都在SQL列
上运行split
将Java正则表达式作为第二个参数。如果要在任意空格上分隔数据,则需要以下内容:
df = sqlContext.createDataFrame(
[('cat \n\n elephant rat \n rat cat', )], ['word']
)
df.select(explode(split(col("word"), "\s+")).alias("word")).show()
## +--------+
## | word|
## +--------+
## | cat|
## |elephant|
## | rat|
## | rat|
## | cat|
## +--------+
要在空白处拆分并删除空行,请添加
where
子句
DF = sqlContext.createDataFrame([('cat \n\n elephant rat \n rat cat\nmat\n', )], ['word'])
>>> (DF.select(explode(split(DF.word, "\s")).alias("word"))
.where('word != ""')
.show())
+--------+
| word|
+--------+
| cat|
|elephant|
| rat|
| rat|
| cat|
| mat|
+--------+
感谢您添加where子句。要获得更完整的解决方案,可以推广到必须报告多个列的情况,请使用“withColumn”而不是简单的“select”,即:df.withColumn('word',explode('word'))。show()这保证了在使用explode之后,DataFrame中的所有其余列仍然存在于输出DataFrame中。这也比指定每个需要选择的列更简单,例如:df.select('col1','col2',…,'colN',explode('word'))。show()correction-advice*