파이썬 191

판다스 컬럼 항목 일괄 변경, 특정 컬럼 기준 정렬, map 매핑

목차 1. 판다스 컬럼의 항목을 일괄 변경하는 방법 replace import pandas as pd # 데이터프레임 생성 df = pd.DataFrame({'expert': [1, 2, 1, 2, 1, 2]}) # 'expert' 칼럼 값 변경 df['expert_2'] = df['expert'].replace({1: 'a', 2: 'b'}) # 결과 출력 print(df) 2. 판다스 특정 컬럼 기준 정렬 sort_values(by = [ , ] ) import pandas as pd # 데이터프레임 생성 df = pd.DataFrame({'a': [1, 3, 2, 1, 2], 'b': [4, 2, 6, 5, 3], 'c': [7, 9, 8, 10, 6]}) # 'a' 컬럼을 기준으로 오름차순 정렬 ..

파이썬/판다스 2024.02.15

iterator, enumerate, iterrows, zip, iter, next

목차 파이썬에서 iterator이터레이터는 반복가능한 iterable한 객체에 순차적으로 요소를 반환하는 객체이다. iterator은 반복 가능한 객체의 요소를 차례대로 가져오면서 메모리를 절약할 수 있다. 대규모 데이터, 무한 데이터 스트림과 같이 모든 요소를 한 번에 로딩하지 않고, 필요할 때마다 요소를 생성하고 반환하기 때문이다. 파이썬에서 자주 쓰이는 함수 3개를 이야기해보자. iterrows 판다스 데이터프레임에서 각 행을 반복문을 사용하여 출력하는 방법이다. import pandas as pd # 예시 DataFrame 생성 data = {'Name': ['John', 'Emily', 'Ryan'], 'Age': [25, 30, 35], 'City': ['New York', 'Paris', '..

map, pandas, pyplot, matplotlib, code

map(적용할 함수, iterable한 대상) 위의 맵함수를 통해 반환되는 iterator 객체는 list나 tuple과 같은 sequence 자료형으로 변환 가능하다. def square(x): return x ** 2 lst = [1, 2, 3, 4, 5] squared_lst = list(map(square, lst)) print(squared_lst) # 출력: [1, 4, 9, 16, 25] 판다스 unique() df['칼럼명'] df.loc[label] df.iloc[index] -preprocess df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis=1, inplace=True) df_can.rename(columns={"OdName":"C..

list is mutable, tuple is immutable, list aliasing, list(), clone by value

목차 우선 mutable은 변할 수 있는, immutable 수정할 수 없는, 변할 수 없다는 뜻을 가진다. 파이썬에서 비슷한 모습을 하고 있는 타입이 list와 tuple이다. list는 mutable하고, tuple은 immutable하다. 그래서 메소드를 쓸 때 차이점이 있는데 이를 살펴보도록 하자. 1. 인덱스값 변경 불가! # create a list and a tuple containing the same elements my_list = [1, 2, 3] my_tuple = (1, 2, 3) # modify the first element of the list my_list[0] = 4 print(my_list) # Output: [4, 2, 3] # try to modify the firs..

파이썬 정규표현식 모듈 re, re.sub, re.findall, re.search

정규표현식 regular expression 모듈인 re모듈은 python에서 문자열의 특정 패턴을 찾거나, 이를 변환하는 데 사용된다. 're' 모듈은 많은 문자열 처리 작업을 수행한다. 1. re.search() 문자열에서 정규식 패턴과 일치하는 첫 번째 위치를 찾음 import re string = "The quick brown fox jumps over the lazy dog" pattern = "quick" match = re.search(pattern, string) if match: print("Match found at index:", match.start()) else: print("Match not found") Match found at index: 4 2. re.sub() 문자열에서..