LiJell's 성장기

08.python_pandas_string_method 본문

Bigdata/파이썬_Python

08.python_pandas_string_method

All_is_LiJell 2022. 1. 2. 21:53
반응형

Modified on Jan 02 2022

# -- coding: utf-8 --
"""
Created on Mon Dec 20 15:18:23 2021

@author: hanju
"""

판다스_문자열 메소드

기본 메소드 : 벡터 연산 불가능 (매 원소마다 반복 불가)

'abc'.upper()
# 'ABC'
'a/b/c'.split('/')[1]

l1 = ['abc','def']
l2 = ['a/b/c','d/e/f']

l1.upper() # 안됨 ㅠ 
l2.upper()
# 따라서 맵 활용

list(map(lambda x: x.upper(), l1))
# ['ABC', 'DEF']

list(map(lambda x: x.split('/'), l2))
# [['a', 'b', 'c'], ['d', 'e', 'f']]

# pandas 메서드 : 벡터화 내장 (매 원소마다 반복 가능)
# Series, DataFrame 적용 가능
from pandas import Series, DataFrame

1) split

Series(l1)
# 0    abc
# 1    def
# dtype: object
s1=Series(l1)
s2=Series(l2)

s2
# 0    a/b/c
# 1    d/e/f

s2.split('/') # 안되요 >> 불가
# 0    [a, b, c]
# 1    [d, e, f]
# dtype: object

2) 대소치환

s1.upper() # 안됨 
s1.str.upper() # 대문자 치환
# 0    ABC
# 1    DEF
# dtype: object
s1.str.lower() # 소문자 치환 (****)
s1.str.title()
# 0    Abc
# 1    Def
# dtype: object

# replace (치환)
s1.str.replace('a','A') # 문자열 치환
s1.str.replace('a','')  # 문자열 삭제
# 0     bc
# 1    def
# dtype: object

# [예제] 천단위 구분기호 처리 
s3 = Series(['1,200','3,000','4,000'])
# 0    1,200
# 1    3,000
# 2    4,000
# dtype: object

s3.sum()
s3.sum() #'1,2003,0004,000' >> 천단위 구분기호 때문에 문자열 결합으로 해석

s3.str.replace(',','').astype(int).sum()
# 8200

3) 패턴확인 : startswith(), endswith, contains

s1.str.startswith('a')
# 0     True
# 1    False
# dtype: bool
s1
s1[s1.str.startswith('a')]      # s1 각 원소에서 'a'로 시작하는 원소 추출
s1[s1.str.endswith('c')]        # s1 각 원소에서 'c'로 끝나는 원소 추출
# 0    abc
# dtype: object
s1[s1.str.contains('e')]        # s1 각 원소에서 'e'를 포함하는 원소 추출

4) 문자열 크기 len()

s1.str.len()                    # 각 원소의 크기
# 0    abc
# dtype: object

5) count 포함되어 있는 개수

Series(['aabca','abcdsa']).str.count('a')
# 0    3
# 1    2
# dtype: int64

6) 문자열 제거 (제거함 : 공백, 문자)

Series(['      cd    ', '             df            '])
Series(['      cd    ', '             df            ']).str.strip().str.len()

s1
# 0    abc
# 1    def
# dtype: object
s1.str.strip('a')              #문자열 제거
Series(['aaaaabaaaca','abcda']).str.strip('a') # 문자열 제거 (중간 값 섹제 불가)
# 0    baaac
# 1      bcd
# dtype: object
Series(['aaaaabaaaca','abcda']).str.replace('a', '') #중간값도 삭제 가능
# 0     bc
# 1    bcd
# dtype: object

7) find 함수 : 위치값 리턴

s6 = Series(['abc@abc.com','avcsd@abc.com'])
a = s6.str.find('@')

# 문자열 색인(추출)
'abcded'[0:3] # 문자열 색인
s6[0:1]       # Series 에서 1번째 원소 추출
# 0    abc@abc.com
# dtype: object

s6.str[0:3]
# 0    abc
# 1    avc
# dtype: object

# [예제] - 이메일 아이디 추출
s6 = Series(['abc@abc.com','avcsd@abc.com'])
a = s6.str.find('@')
a
s6.map(lambda x : x[:x.find('@')])


list(map(lambda x, y: x[0:y], s6, a))
#['abc', 'avcsd']

8) 문자열 삽입 pad

s1.str.pad(5,            # 총 자리수
            'left',       # 삽입할 방향
            '!')          # 삽입할 글자

s1.str.pad(5,'left','!')
# 0    !!abc
# 1    !!def
# dtype: object
s1.str.pad(5,'right','^')
# 0    abc^^
# 1    def^^
# dtype: object
s1
# 0    abc
# 1    def
# dtype: object

9) 문자열 결합 cat

'a'+'b' # 'ab'
'a'*3   # 'aaa'

s4 = Series(['abc','def','123'])
s4.str.cat()
# 'abcdef123' >>>  Series 내 서로 다른 원소 결합
s4.str.cat(sep='/') # 'abc/def/123' >> Series 내 서로 다른 원소를 구분기호와 함께 결함
# 'abc/def/123'
s5 = Series([['a','b','c'],['d','e','f']])
# 0    [a, b, c]
# 1    [d, e, f]
# dtype: object

s5.str.join(sep='') # >> Series 내 각 원소 내부의 문자열 결합
# 0    abc
# 1    def
# dtype: object
s5.str.join(sep=',')
# 0    a,b,c
# 1    d,e,f
# dtype: object
반응형

'Bigdata > 파이썬_Python' 카테고리의 다른 글

10.python_replace_method  (0) 2022.01.03
09.python_pandas_arithmetic_method  (0) 2022.01.02
07. Pandas _ Series, DataFrame  (0) 2022.01.01
06.python_str_method  (0) 2021.12.20
05.python_numpy  (0) 2021.12.15
Comments