Python

Pandas map, apply 예제

Yukart 2022. 2. 16. 09:25
반응형

값 대치

값 대치 (딕셔너리)

s = pd.Series([1, 2, 3]) # 3행 1열의 샘플 데이터

mapping = { 1:"drop", 2:"the", 3:"table" }  # 딕셔너리 구조의 맵핑할 데이터
s1 = s.map(mapping) # 딕셔너리를 인자로 map 호출
print(s1)

# 결과
0     drop
1      the
2    table
dtype: object

값 대치 (함수)

s.map(lambda x: x**2) # 각각 제곱

# 결과
0    1
1    4
2    9
dtype: int64

값 변환(함수 호출)

# 제곱 함수 선언
def squared(value):
	return value * value

# apply
s.apply(squared)

# 결과
0    1
1    4
2    9
dtype: int64

값 변환(람다 함수 호출)

s.apply(lambda value : value * value)

# 결과
0    1
1    4
2    9
dtype: int64

📙 특이사항

예제를 작성하면서 새로 알게된 점은 위 함수 모두 원본데이터 s의 복제본을 return 해줌으로 데이터 원본의 변경 없이 작업 할 수 있다.

🔗참조 링크

https://wikidocs.net/75115

https://pandas.pydata.org/docs/reference/api/pandas.Series.html

반응형

'Python' 카테고리의 다른 글

[Python] Selenium 사용법 정리  (0) 2023.09.18
Pandas IO File Format  (0) 2022.03.27
Pandas 결측치 예제  (0) 2022.02.16
Pandas 데이터 타입  (0) 2022.02.16