apply map applymap

Published by onesixx on

import pandas as pd
import numpy as np
# https://zephyrus1111.tistory.com/90
df = pd.DataFrame({'A': [10, 20, 30],
                   'B': [5, 15, 25]})

df.apply(np.sum, axis=0) # 열합 A 60, B 45
df.apply(np.sum, axis=1) # 행합 10+5, 20+15, 30+25

# 함수적용
def difference_max_min(column):
    return column.max() - column.min()
df.apply(difference_max_min) # 열 최대값-최소값 A 20, B 20

## 열기준
df.apply(lambda x:np.square(x) if x.name in ['A','B'] else x)# ,  axis=0)
# 10**2, 20**2, 30**2, 5**2, 15**2, 25**2
df.apply(lambda x:np.square(x) if x.name in ['A'] else x)

## 행기준
df.apply(lambda x:np.square(x) if x.name in [0,1] else x, axis=1)
df.apply(lambda x:np.square(x) if (x.name+1)%2==0 else x,axis=1)

## 적용함수에 인자를 받아서 처리
def col_sum(x,a,b):
    return a*x+b
df.apply(col_sum, args=(3,1))

df.apply(lambda x: col_sum(x,3,1))

## 특정조건에 대해서 
df.apply(lambda x:(np.square(x['A']), np.log(x['B'])) if x['B']>0 else x, axis=1)
https://zephyrus1111.tistory.com/64

apply

예제 dataframe

df = pd.DataFrame([
    [ 1,  2,  3,  4,  5],
    [ 6,  7,  8,  9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20]
], index = ['ridx1', 'ridx2', 'ridx3', 'ridx4'],
   columns=['colNm1', 'colNm2', 'colNm3', 'colNm4', 'colNm5'])

axis 0=>행방향 1=>열방향

# 행기준 (아래로)
df.apply(np.cumsum, axis=0)
# 열기준 (오른쪽으로)
df.apply(np.cumsum, axis=1) 
df['행 합'] = df.sum(axis=1)

df.loc['열 합']= df.sum(axis=0)

df.append(df,ignore_index=True)

rounding values ​​in each column 

df = px.data.stocks()

df.iloc[:, 1:] = df.iloc[:, 1:].apply(lambda x: round(x, 2))

Map

import math
# math.ceil 
# round
# math.floor

list( map(math.ceil, [1.1,2.2,3.3,4.4,5.5,6.6]))
# [2, 3, 4, 5, 6, 7]

lambda

def xxx(x:int):
    return x*x

list( map (xxx, [1,2,3,4,5]) )
list( map(lambda x:x*x, list(range(1,6))) )
# [1, 4, 9, 16, 25]

filter

def isEven(x):
    return x%2==0

list( filter(isEven, [1,2,3,4,5]) )
list( filter(lambda x:x%2==0, list(range(1,6))) )
#[2, 4]

Categories: pandas

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x