16. 데이터프레임 응용 -함수 매핑(mapping)

김동웅·2021년 9월 3일
0

Pandas with python

목록 보기
16/23

1. 함수 매핑

  • 데이터프레임에 함수를 매핑하는 방법
  • 데이터를 집계하는 그룹연산
  • 데이터프레임을 합치거나 다양한 형태로 구조를 변경하는 방법 등등

함수 매핑이란?

시리즈 또는 데이터프레임의 개별 원소를 특정 함수에 일대일 대응시키는 과정이다.
사용자가 직접 만든 함수(lambda 함수 포함)를 적용할 수 있기 때문에 판다스 기본 함수로 처리하기 힘든 복잡한 연산을 데이터프레임 등 판다스 객체에 적용하는 것이 가능하다.

1-1. 개별 원소에 함수 매핑

시리즈 객체에 apply() 메소드를 적용하면 인자로 전달하는 매핑 함수에 시리즈의 모든 원소를 하나씩 입력하고 함수의 리턴값을 돌려받는다.

  • 시리즈의 원소에 함수 매핑 : Serise 객체.apply(매핑함수)
import seaborn as sns

def add_10(n):
    return n+10

def add_two_obj(a,b):
    return a+b

titanic = sns.load_dataset('titanic')

df = titanic.loc[:,['age','fare']]
df['ten']=10
print(df.head())

sr1 = df['age'].apply(add_10)
print(sr1.head())

# 시리즈 객체와 숫자에 적용: 2개의 인수(시리즈+숫자)
sr2 =df['age'].apply(add_two_obj,b=10) # a=df['age']의 모든 원소, b=10
print(sr2.head())

# lambda 함수 활용 : 시리즈 객체에 적용
sr3 =df['age'].apply(lambda x = add_10(x)) # x = df['age']
print(sr3.head()


데이터프레임에 applymap()메소드를 활용하면 매핑 함수에 데이터프레임의 각 원소를 하나씩 넣어서 리턴값으로 돌려받는다.

  • 데이터프레임에 함수매핑 : DataFrame객체.applymap()
import seaborn as sns

titanic = sns.load_dataset('titanic')

df = titanic.loc[:,['age','fare']]

print(df.head())
print('\n')

def add_10(n):
    return n+10


df_map = df.applymap(add_10)
print(df_map.head())


1-2. 시리즈 객체에 함수 매핑

  • 데이터프레임의 각 열에 함수 매핑
    apply(axis=0)메소드를 적용하면 모든 열을 하나씩 분리하여 매핑 함수의 인자로 각 열이 전달된다.
  • 데이터프레임의 열에 함수 매핑 : DataFrame객체.apply(매핑함수,axis=0)

ex1)

import seaborn as sns

titanic = sns.load_dataset('titanic')

df = titanic.loc[:,['age','fare']]

print(df.head())
print('\n')

def missing_value(series):
    return series.isnull()

result = df.apply(missing_value,axis=0)
print(result.head())

ex2)

import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:,['age','fare']]

def min_max(x):
    return x.max()-x.min()


result = df.apply(min_max,axis=0) # default axis=0

print(result)
print(type(result))
  • 데이터프레임의 각 행에 함수 매핑
  • 데이터프레임의 행에 함수 매핑 : Dataframe객체.apply(axis=1) 적용

import seaborn as sns

titanic = sns.load_dataset('titanic')

df = titanic.loc[:,['age','fare']]
df['ten']=10

def add_two_obj(a,b):
    return a+b

print(df.head())


df['add'] = df.apply(lambda x : add_two_obj(x['age'],x['ten']),axis=1)

print(df.head())

1-2. 데이터프레임 객체에 함수 매핑

  1. 데이터프레임 객체
  • 데이터프레임 객체에 함수 매핑 : DataFrame 객체.pipe(매핑함수)
from os import add_dll_directory
import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:,['age','fare']]

df['ten']=10

def max_min(x):
    return x.max()-x.min()

def add_10(x):
    return x+10

def add_two_obj(a,b):
    return a+b

# 각 열의  NaN 찾기 - 데이터프레임을 전달하면 데이터프레임 반환
def missing_value(x):
    return x.isnull()


# 각 열의  NaN 개수 반환 - 데이터프레임을 전달하면 시리즈 전환
def missing_count(x):
    return missing_value(x).sum()


# 데이터프레임의 총 NaN 개수 - 데이터프레임을 전달하면 값 반환
def total_number_missing(x):
    return missing_count(x).sum()

print('원본','\n',df.head())

# 데이터프레임의 행 매핑
df['added'] = df.apply(lambda x : add_two_obj(x['age'],x['ten']),axis=1)
print(df.head())

# 데이터프레임의 열 매핑
result0 = df.apply(max_min,axis=0)
print(result0)

# 데이터프레임 원소에 함수매핑
result1 = df.applymap(add_10)
print(result1.head())

# 데이터프레임 객체에 함수매핑
result_df = df.pipe(missing_value)
print(result_df.head())
print(type(result_df))

# 데이터프레임 객체에 함수매핑
result_series = df.pipe(total_number_missing)
print(result_series)
print(type(result_series))




0개의 댓글