Transforming Data With Pandas

2020. 1. 18. 16:32Python programming

 

(1) Series.map( )

Series.map(function_name) 이런 식으로 function 적용시키는 method임  

(2) Series.apply()

def label(element, x):
    if element > x:
        return 'High'
    else:
        return 'Low'
    
economy_impact_apply = happiness2015['Economy'].apply(label, x=0.8)

이런 식으로 어떤 Series에 element-wise하게 함수 적용시키고 싶을 때 apply method를 쓴다.

단, apply 메소드는 vectorization이 없을 때만 쓸 것! 왜냐면 pandas uses vectorization, the process of applying operations to whole series at once, to optimize performance.

ex)
# factors = ['Economy', 'Family', 'Health', 'Freedom', 'Trust', 'Generosity'] 

def v_counts(col): 
    num = col.value_counts() 
    den = col.size 
    return num/den 

v_counts_pct = factors_impact.apply(v_counts) 
 

==> 결과

 

 

(3) DataFrame.applymap( )

it can apply functions element-wise to multiple columns at once 예를 들어, 테이블 전체에 한번에 함수 적용할 때

     ex) 여섯 개 컬럼에 한 번에 적용 

def label(element): 
    if element > 1: 
        return 'High' 
    else: 
        return 'Low' 
economy_apply = happiness2015['Economy'].apply(label) 

factors = ['Economy', 'Family', 'Health', 'Freedom', 'Trust', 'Generosity'] 

factors_impact = happiness2015[factors].applymap(label)

 

 

(4) pd.melt() 

pivot 테이블 만들기 - 데이터프레임 분해해서 다시 subtotal 구하는 pivot 테이블 만들기 

ex) pd.melt(happy_two, id_vars=['Country'], value_vars=['Economy', 'Family', 'Health'])
   country 기준으로 economy, family, health 세 컬럼의 subtotal 을 구해서 요약된 데이터프레임 만들어라,
   happy_two 라는 새로운 subset으로 reshape 해라 

 

(5) df.pivot_table()

또다른 pivot 테이블 만드는 방법 - tidy data 형태로 구성

Use the df.pivot_table() method to create a pivot table from the melt dataframe. 

ex) year 기준으로 aggregate할 때 
#Concatenate happiness2015, happiness2016, and happiness2017.
combined = pd.concat([happiness2015, happiness2016, happiness2017])

#Create a pivot table listing the mean happiness score for each year. Since the default aggregation function is the mean, we excluded the `aggfunc` argument.
pivot_table_combined = combined.pivot_table(index = 'Year', values = 'Happiness Score')