IT

파이썬 추가/수정/삭제/검색/정렬 (CRUD)

astrocker 2020. 12. 29. 01:07
반응형

CRUD는 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create(생성), Read(읽기), Update(갱신), Delete(삭제)를 묶어서 일컫는 말이다. 사용자 인터페이스가 갖추어야 할 기능(정보의 참조/검색/갱신)을 가리키는 용어로서도 사용된다. https://ko.wikipedia.org › wiki › CR... CRUD - 위키백과, 우리 모두의 백과사전

 

라이브러리 호출 및 예제 작성

import pandas as pd # 데이터 처리용 라이브러리
import numpy as np  # 수치해석용 라이브러리

sr=pd.Series([10,20,30,40,50],
             index=['a','b','c','d','e'],
             dtype=int,name='kor')

 

수정, 추가

sr[0]=100 # sr['a']=100, sr.loc['a']=100, sr.iloc[0]=100
sr        # 값 수정
Result :
a    100
b     20
c     30
d     40
e     50
Name: kor, dtype: int64

sr[1:3]=2
sr
Result :
a    100
b      2
c      2
d     80
e    100
Name: kor, dtype: int64

sr[1:3]=[11,22]
sr
Result :
a    100
b     11
c     22
d     80
e    100
Name: kor, dtype: int64

sr['f']=200 # 인덱스 값이 있으면 수정, 없으면 추가
sr
Result :
a    100
b     11
c     22
d     80
e    100
f    200
Name: kor, dtype: int64

 

문자열

sr=pd.Series(['홍길동','이순신','이황','김철수','김순이'],
             index=['a','b','c','d','e'])
sr
a    홍길동
b    이순신
c     이황
d    김철수
e    김순이
dtype: object

sr.str[0] # string method 객체 : value의 첫글자만 출력
a    홍
b    이
c    이
d    김
e    김
dtype: object

sr.str.contains('이')
a    False
b     True
c     True
d    False
e     True
dtype: bool

sr[sr.str.contains('이')]
b    이순신
c     이황
e    김순이
dtype: object

sr[sr.str.contains('^이')] # ^는 시작 메타문자, 문자 앞에 붙여야 함. 정규 표현식
b    이순신
c     이황
dtype: object

sr[sr.str.contains('이$')] # $는 종료 메타문자, 문자 끝에 붙여야 함. 정규 표현식
e    김순이
dtype: objec

sr[sr.str.contains('이[순이황]')]
b    이순신
c     이황
dtype: object

sr[sr.str.contains('홍길|순신')]
a    홍길동
b    이순신
dtype: object

sr.index.str.contains('c') # 인덱스가 문자열일 때 조작
array([False, False,  True, False, False])

sr.drop('b') # 인덱스를 사용하여 삭제, 메모리에만 적용
a    홍길동
c     이황
d    김철수
e    김순이
dtype: object

sr.drop(['c'],inplace=True) # inplace 옵션은 sr 변수에 저장
sr
a    홍길동
d    김철수
e    김순이
dtype: object

 

정렬

sr=pd.Series([10,20,30,40,50],
             index=['a','b','c','d','e'],
             dtype=np.int32,name='kor') # list, dict, tuple 사용. 
sr['b']=100
sr['a']=40
sr
a     40
b    100
c     30
d     40
e     50
Name: kor, dtype: int32

sr.sort_index()
a     40
b    100
c     30
d     40
e     50
Name: kor, dtype: int64

sr.sort_values(ascending=False) # False는 내림차순
b    100
e     50
d     40
a     40
c     30
Name: kor, dtype: int64

 

 

728x90
반응형