2016-07-05 2 views
8

단어 목록이 들어있는 DataFrame에서 각 단어가 자체 행에있는 DataFrame으로 변환하고 싶습니다.PySpark에서 분해하십시오

DataFrame에서 열을 어떻게 폭발합니까?

다음은 각 코드 줄의 주석 처리를 제거하고 다음 주석에 나열된 오류를 얻을 수있는 예제입니다. 파이크 2.7에서 스파크 1.6.1을 사용한다.

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() 

답변

13

explodesplit는 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| 
## +--------+ 
6

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| 
+--------+ 
+0

추가 된 부분을 가져 주셔서 감사합니다. – user1982118

+1

두 개 이상의 열을보고해야하는 경우에 일반화 할 수있는 좀 더 완벽한 솔루션의 경우 간단한 '선택'대신 'withColumn'을 사용하십시오. df.withColumn ('word', explode ('word')) .show() 이렇게하면 폭발을 사용하고 나면 DataFrame의 나머지 모든 열이 출력 DataFrame에 계속 표시됩니다. 이것은 또한 선택해야하는 모든 열을 지정하는 것보다 간단합니다. 예 : df.select ('col1', 'col2', ..., 'colN', explode ('word')) –

관련 문제