본문 바로가기
파이썬

파이썬 PySpark에서 폭발

by º기록 2020. 11. 2.
반응형

단어 목록이 포함 된 DataFrame에서 각 단어가 자체 행에있는 DataFrame으로 변환하고 싶습니다.

DataFrame의 열을 어떻게 분해합니까?

다음은 각 코드 행의 주석을 해제하고 다음 주석에 나열된 오류를 얻을 수있는 몇 가지 시도에 대한 예제입니다. 저는 Python 2.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'])
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()

조언 부탁드립니다

 

해결 방법

 

explode split 는 SQL 함수입니다. 둘 다 SQL Column 에서 작동합니다. 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|
## +--------+

 

참조 페이지 https://stackoverflow.com/questions/38210507

 

 

반응형

댓글