파이썬/파이썬 일반 꿀팁(8)
-
파이썬 리스트 끼리의 대소비교
num_1=[2,8,3,4,5] num_2=[4,6,3,1,3] class comparable_list(list): def __lt__(self, other): return all(x y for x, y in zip(self, other)) n1 = comparable_list(num_1); n2 = comparable_list(num_2); print(n1 n4) #..
2022.08.02 -
더미변수 다시 원래대로 돌리기
In [1]: import pandas as pd In [2]: s = pd.Series(['a', 'b', 'a', 'c']) In [3]: s Out[3]: 0 a 1 b 2 a 3 c dtype: object In [4]: dummies = pd.get_dummies(s) In [5]: dummies Out[5]: a b c 0 1 0 0 1 0 1 0 2 1 0 0 3 0 0 1 In [6]: s2 = dummies.idxmax(axis=1) In [7]: s2 Out[7]: 0 a 1 b 2 a 3 c dtype: object idxmax() 함수 쓰면 됨
2022.07.11 -
리스트 순서 유지하면서 중복 제거 방법
arr = [6, 5, 6, 4, 4, 1, 1, 2, 3, 9, 8, 7, 9, 8, 7] result1 = dict.fromkeys(arr) # 리스트 값들을 key 로 변경 print(result1) result2 = list(result1) # list(dict.fromkeys(arr)) print(result2) dict.fromkeys(리스트 자료형)을 이용해서 중복이 제거된 키 값들로 변환된 것을 볼 수 있습니다. list(dict.fromkeys(리스트 자료형)을 이용해서 키 값으로 변환된 것들을 다시 리스트로 변환하는 것을 볼 수 있습니다. 이방법 또한 순서가 유지되는 것을 볼 수 있습니다.
2022.05.12 -
딕셔너리를 활용해서 변수 생성
import pandas as pd df = pd.DataFrame({'col1': [1, 2, 2, 3, 1], 'col2': ['negative', 'positive', 'neutral', 'neutral', 'positive']}) conversion_dict = {'negative': -1, 'neutral': 0, 'positive': 1} df['converted_column'] = df['col2'].replace(conversion_dict) print(df.head()) 결과) col1 col2 converted_column 0 1 negative -1 1 2 positive 1 2 2 neutral 0 3 3 neutral 0 4 1 positive 1
2022.04.05 -
itertools (순열, 조합)
파이썬으로 코딩할 때, 종종 순열, 조합을 구현할 때가 많다. 이럴 때 일일이 여러 반복문을 사용해서 구현하지 말고 표준 라이브러리인 itertools를 사용하자. ㅇ combinations 조합을 표현할 때 사용되는 메소드이다. 한 리스트에서 중복을 허용하지 않고 모든 경우의 수를 구하는 것이다. 반환되는 항목의 수는 n! / r! / (n - r)!이다. 사용법은 다음과 같다. - 예시) from itertools import combinations _list = [1, 2, 3] combi = list(combinations(_list, 2)) print(combi) # [(1, 2), (1, 3), (2, 3)] # 갯수 별로 조합을 반복할 수 있다. for i in range(1, len(_li..
2021.06.30 -
반복문에서 zip 활용
ㅇ 몇 개의 칼럼이 겹치는 여러 데이터가 있을 때 겹치는 칼럼이 조건으로 들어가는 데이터를 세부적으로 뽑아주고 싶을 때 반복문에서 zip 을 사용한다 ㅇ 예시)
2021.06.01