Spark & Hadoop/Pyspark & SparkSQL

[Pyspark] 데이터 프레임에서 특정 컬럼만 필터링하는 방법 (select)

YSY^ 2023. 10. 2. 17:58

해당 포스팅은 데이터 프레임에서 특정 컬럼만 필터링하는 방법을 소개한다.

활용 데이터

1800.csv
0.06MB

사전 작업

from pyspark.sql.types import StringType, IntegerType, FloatType
from pyspark.sql.types import StructType, StructField

schema = StructType([ \
                     StructField("stationID", StringType(), True), \
                     StructField("date", IntegerType(), True), \
                     StructField("measure_type", StringType(), True), \
                     StructField("temperature", FloatType(), True)])
                     
df = spark.read.schema(schema).csv("1800.csv")
minTemps = df.filter(df.measure_type == "TMIN")

 

1. pandas와 같이 리스트 형식으로 컬럼을 필터링한다.

# Select only stationID and temperature
stationTemps = minTemps[["stationID", "temperature"]]

2. select 메소드를 활용한다.

2-1) 컬럼이름을 직접 입력해서 컬럼을 select한다.

stationTemps = minTemps.select("stationID", "temperature")

2-2) col, column 메소드를 활용하여 컬럼을 select한다.

  • col이나 column이나 같음
  • 요즘 잘 쓰지 않는 방식임 (2-1방법이 더 간편하기 때문)
from pyspark.sql.functions import col,column
stationTemps = minTemps.select(col("stationID"), column("temperature"))

2-3) 데이터프레임이름.컬럼이름 으로 지칭한다.

stationTemps = minTemps.select(minTemps.stationID)

 

 
728x90
반응형