Spark DataFrame 열을 Python 목록으로 변환
두 개의 열, mvv 및 count가있는 데이터 프레임에서 작업합니다.
+---+-----+
|mvv|count|
+---+-----+
| 1 | 5 |
| 2 | 9 |
| 3 | 3 |
| 4 | 1 |
mvv 값과 카운트 값을 포함하는 두 개의 목록을 얻고 싶습니다. 같은 것
mvv = [1,2,3,4]
count = [5,9,3,1]
그래서 다음 코드를 시도했습니다. 첫 번째 줄은 파이썬 행 목록을 반환해야합니다. 첫 번째 값을보고 싶었습니다.
mvv_list = mvv_count_df.select('mvv').collect()
firstvalue = mvv_list[0].getInt(0)
하지만 두 번째 줄에 오류 메시지가 나타납니다.
AttributeError : getInt
왜 이런 식으로 작동하지 않는지보십시오. 먼저 행 유형 에서 정수를 가져 오려고 합니다. 수집 결과는 다음과 같습니다.
>>> mvv_list = mvv_count_df.select('mvv').collect()
>>> mvv_list[0]
Out: Row(mvv=1)
다음과 같은 것을 취하면 :
>>> firstvalue = mvv_list[0].mvv
Out: 1
당신은 mvv
가치 를 얻을 것 입니다. 배열의 모든 정보를 원하면 다음과 같이 할 수 있습니다.
>>> mvv_array = [int(row.mvv) for row in mvv_list.collect()]
>>> mvv_array
Out: [1,2,3,4]
그러나 다른 열에 대해서도 동일하게 시도하면 다음과 같은 결과가 나타납니다.
>>> mvv_count = [int(row.count) for row in mvv_list.collect()]
Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method'
이것은 count
내장 메서드 이기 때문에 발생합니다 . 열의 이름은 count
. 이를위한 해결 방법은 열 이름을 다음 count
과 _count
같이 변경하는 것입니다 .
>>> mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count")
>>> mvv_count = [int(row._count) for row in mvv_list.collect()]
그러나 사전 구문을 사용하여 열에 액세스 할 수 있으므로이 해결 방법은 필요하지 않습니다.
>>> mvv_array = [int(row['mvv']) for row in mvv_list.collect()]
>>> mvv_count = [int(row['count']) for row in mvv_list.collect()]
그리고 마침내 작동합니다!
하나의 라이너를 따라 가면 원하는 목록이 제공됩니다.
mvv = mvv_count_df.select("mvv").rdd.flatMap(lambda x: x).collect()
이렇게하면 모든 요소가 목록으로 제공됩니다.
mvv_list = list(
mvv_count_df.select('mvv').toPandas()['mvv']
)
다음 코드가 도움이 될 것입니다.
mvv_count_df.select('mvv').rdd.map(lambda row : row[0]).collect()
내 데이터에서 다음과 같은 벤치 마크를 얻었습니다.
>>> data.select(col).rdd.flatMap(lambda x: x).collect()
0.52 초
>>> [row[col] for row in data.collect()]
0.271 초
>>> list(data.select(col).toPandas()[col])
0.427 초
결과는 동일합니다
아래 오류가 발생하는 경우 :
AttributeError : 'list'개체에 'collect'속성이 없습니다.
이 코드는 문제를 해결합니다.
mvv_list = mvv_count_df.select('mvv').collect()
mvv_array = [int(i.mvv) for i in mvv_list]
참고 URL : https://stackoverflow.com/questions/38610559/convert-spark-dataframe-column-to-python-list
'IT박스' 카테고리의 다른 글
SQL 쿼리 내에서 두 필드를 합산하는 방법 (0) | 2020.10.31 |
---|---|
Webstorm "Reformatting Source Code"를 만들어 큰 따옴표를 작은 따옴표로 변경하는 방법은 무엇입니까? (0) | 2020.10.31 |
Pandas MultiIndex 앞에 수준 추가 (0) | 2020.10.31 |
Django에서 필터로 최신 기록 가져 오기 (0) | 2020.10.31 |
iOS에서 "뒤로"탐색 단추 동작 처리 시도 (0) | 2020.10.31 |