일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 크롤링
- python
- instance
- matplotlib
- Agile
- data analyze
- angular
- Scrum
- Method
- tensorflow
- opencv
- visualizing
- 애자일
- ECS
- TypeScript
- 자바스크립트
- pandas
- DANAWA
- algorithm
- javascript
- 다나와
- adaptive life cycle
- data
- 프로젝트
- keras
- webcrawling
- analyzing
- AWS
- Crawling
- Project
Archives
- Today
- Total
LiJell's 성장기
06.python_str_method 본문
반응형
Modified on Dec 31
# -- coding: utf-8 --
"""
Created on Thu Dec 16 15:32:15 2021
@author: hanju
"""
문자열 메서드
문자열 처리와 관련된 메서드
1. 기본 메서드 : 벡터 연산 불가 (매 원소마다 반복 불가)
'abc'.upper()
'a/b/c'.split('/')
'a/b/c'.split('/')[1]
l1=['abc', 'def']
l2=['a/b/c','d/e/f']
l1.upper() # 불가
l2.split() # 불가
map(lambda x: x.upper(),l1) # 맵 지정
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
1) split
from pandas import Series, Dataframe
l1
# ['abc', 'def']
Series(l1)
# 0 abc
# 1 def
# dtype: object
s1= Series(l1)
l2
# ['a/b/c', 'd/e/f']
Series(l2)
# 0 a/b/c
# 1 d/e/f
# dtype: object
s2=Series(l2)
s2.split('/')
'''
AttributeError: 'Series' object has no attribute 'split'
'''
s2.str.split('/') #str 문자로 지정 문서화..
# 0 [a, b, c]
# 1 [d, e, f]
# dtype: object
2) 대소 치환
s1
# 0 abc
# 1 def
# dtype: object
s1.str.upper()
'''
0 ABC
1 DEF
dtype: object
'''
s1.str.lower()
'''
0 abc
1 def
dtype: object
'''
s1.str.title()
'''
0 Abc
1 Def
dtype: object
'''
3) replace
s1.str.replace('a','A')
# 0 Abc
# 1 def
# dtype: object
s1.str.replace('a', '') # 매우 중요함 significantly important!
# 0 bc
# 1 def
# dtype: object
예제 - 천단위 구분기호 처리
s3= Series(['1,200','3,000','4,000'])
s3.sum()
# '1,2003,0004,000'
# 천 단위 구분기호 때문에 문자로 입력된 값이라 문자열 결합으로 인식
# 구분기호 문제네? 문자로 인식되어 있네? 더 해줘야 되네
s3.str.replace(',','').astype('int').sum()
#8200
s3= Series(['1,200','3,000','4,000'])
s3 = s3.str.replace(',','')
sum(list(map(lambda x: int(x), s3)))
#8200
4) 패턴 확인 : startswitch, endswitch, contains
s1
# 0 abc
# 1 def
# dtype: object
s1.str.startswith('a')
# 0 True
# 1 False
# dtype: bool (조건을 만들 때 쓰는 dtype)
s1[s1.str.startswith('a')] # s1 각 원소에서 'a'로 시작하는 원소 추출
# 0 abc
# dtype: object
s1[s1.str.endswith('c')] # s1 각 원소에서 'c'로 끝나는 원소 추출
s1[s1.str.contains('e')] # s1 각 원소에서 'e'로 끝나는 원소를 추출해줘
문자열 크기(길이) len()
s1.str.len()
# 0 3
# 1 3
# dtype: int64
count 포함 개수
Series(['aabbbb', 'abcdadd']).str.count('a')
# 0 2
# 1 2
# dtype: int64
제거 함수 (공백, 문자)
Series([' cd ', ' df '])
Series([' cd ', ' df ']).str.strip()
# 0 cd
# 1 df
# dtype: object
Series([' cd ', ' df ']).str.strip().str.len()
# Out[137]:
# 0 2
# 1 2
# dtype: int64
s1
# 0 abc
# 1 def
# dtype: object
s1.str.strip('a') # 문자열 제거 양쪽 끝
Series(['aaaabaaabcd', 'abcdaa']).str.strip('a')
# 0 baaabcd
# 1 bcd
# dtype: object
Series(['aaaabaaabcd', 'abcdaa']).str.replace('a','') # 전체에서 제거
# 0 bbcd
# 1 bcd
# dtype: object
find (위치값 return)
s3= Series(['abc@drwill.kr','abcdef@drwill.com'])
s3.str.find('@')
문자열 색인 (추출)
'abcde'[0:3] # 문자열 색인
s3[0:3] # Series에서 1번째, 2번째, 3번째 원소 추출
s3.str[0:3] # Series에서 각 원소마다 1번째, 2번째, 3번째 문자열 추출
이메일 아이디 추출
s4= Series(['drwill@naver.com', 'zzuyu@drwill.kr'])
vno=s4.str.find('@')
vno
list(map(lambda x, y : x[0:y], s4, vno)) # y 추출 s4범위 본문 x, vno위치정보
# ['drwill', 'zzuyu']
s4= Series(['drwill@naver.com', 'zzuyu@drwill.kr'])
s4.map(lambda x : x[0:x.find('@')])
vnoo=s3.str.find('@')
list(map(lambda x, y : x[0:y], s3, vnoo))
s4.str[0:s4.str.find('@')]
s4.str[0:s4.str.find('@')[0]]
s4.str[0:s4.str.find('@')[1]]
s4.str[0:s4.str.find('@')[1]][1]
s4.str[0:s4.str.find('@')[1]][0]
pad : 문자열 삽입
s1.str.pad(5, # 총 자리수
'left', # 삽입 방향
'!') # 삽입 글자 (character만 가능)
s1
# 0 abc
# 1 def
# dtype: object
s1.str.pad(5,'left','!')
# Out[181]:
# 0 !!abc
# 1 !!def
# dtype: object
s5= Series(['abcd','def'])
s5.str.pad(5,'right','?')
# 0 abcd?
# 1 def??
# dtype: object
문자열 결합
'a' + 'b'
'a'*3
s6= Series(['abc','def', '123'])
s6.str.cat()
#'abcdef123' 다 합쳐버림
s6.str.cat(sep='/') # 합치면서 구분해주기
# 'abc/def/123'
s6.str.cat(sep=',')
# 'abc,def,123'
s7= Series([['a','b','c'],['d','e','f']])
s7
s7.str.join(sep='') #Series 내 각 원소 내부의 문자열을 결합 (공백)
# 0 abc
# 1 def
# dtype: object
s7.str.join(sep=',') #Series 내 각 원소 내부의 문자열을 결합 후 , 로 구분
# 0 a,b,c
# 1 d,e,f
# dtype: object
반응형
'Bigdata > 파이썬_Python' 카테고리의 다른 글
08.python_pandas_string_method (0) | 2022.01.02 |
---|---|
07. Pandas _ Series, DataFrame (0) | 2022.01.01 |
05.python_numpy (0) | 2021.12.15 |
04.python_def_lambda_map (0) | 2021.12.15 |
03.python_conditional_statements_loop (0) | 2021.12.15 |
Comments