본문 바로가기
파이썬

파이썬 Pyspark DataFrame의 선택한 행에서 특정 필드 가져 오기

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

JSON 파일에서 pyspark 를 통해 빌드 된 Spark DataFrame이 있습니다.

sc = SparkContext()
sqlc = SQLContext(sc)

users_df = sqlc.read.json('users.json')

이제 _id 필드가있는 chosen_user 데이터에 액세스하려고합니다. 내가 할 수있는

print users_df[users_df._id == chosen_user].show()

그리고 이것은 나에게 사용자의 전체 행을 제공합니다. 그러나 사용자 성별과 같이 행에 특정 필드 하나만 원한다고 가정하면 어떻게 얻을 수 있습니까?

 

해결 방법

 

필터링하고 선택하기 만하면됩니다.

result = users_df.where(users_df._id == chosen_user).select("gender")

또는 col

from pyspark.sql.functions import col

result = users_df.where(col("_id") == chosen_user).select(col("gender"))

마지막으로 PySpark Row 는 일부 확장이있는 tuple 이므로 예를 들어 flatMap 을 사용할 수 있습니다.

result.rdd.flatMap(list).first()

또는 다음과 같이 map :

result.rdd.map(lambda x: x.gender).first()

 

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

 

 

반응형

댓글