
심심해서만들어보는함수 - Pandas 인덱싱 메서드로 컬럼 순서 변경하기딥상어동의 딥한 프로그래밍/Python2022. 7. 9. 11:17
Table of Contents

Docstring - Google Syle
함수 내용 - 판다스 Indexing 메서드와 그 에 따라 컬럼 순서가 어떻게 바뀌는지 확인
고려 내용 - np.intersect1d를 이용하여 df안에 있는 컬럼인지 체크
- iloc의 경우 dict를 이용하여 원본 df의 컬럼 순서를 저장
def change_col_order(method_type: str, col_list: list, df: pd.DataFrame):
"""change the col order using iloc/loc/concat/column_indexing
change the col order using python method
Args:
method_type (str): method_name
col_list (list): column_list
df (pd.DataFrame): dataframe
Return:
df with changed columns
Rasies:
if col_list do not exist in df.columns then exit
"""
# check if col_list exists in df.columns
if np.array_equal(np.sort(np.intersect1d(np.array(col_list), np.array(df.columns.tolist()))), np.sort(np.array(col_list))) == False:
print("잘못된 컬럼을 입력하셨습니다.")
return
# df col changes with method_type
if method_type == 'loc':
return df.loc[:, col_list]
elif method_type == 'iloc':
col_dict = {}
for col, i in zip(df.columns.tolist(), range(len(df.columns.tolist()))):
col_dict[col] = i
col_list_iloc = [col_dict[key] for key in col_list]
return df.iloc[:, col_list_iloc]
elif method_type == 'concat':
return pd.concat([df[col] for col in col_list], axis=1)
elif method_type == 'column_indexing':
return df[col_list]
else:
print("잘못된 메서드를 입력하셨습니다.")
'딥상어동의 딥한 프로그래밍 > Python' 카테고리의 다른 글
[Python] 클래스와 상속 기초 예제 (0) | 2022.04.24 |
---|---|
[pytest] TDD, 초간단 pytest 실행해보기 (0) | 2022.04.17 |
[Python] PEP 8 스타일 가이드 중 헷갈리는 것 정리 (0) | 2022.04.11 |
파이썬을 효과적으로 사용하기 위한 몇가지 방법들 (0) | 2022.03.06 |
[Python] Dot.점 의 의미 (0) | 2022.02.06 |
@딥상어동의 딥한생각 :: 딥상어동의 딥한생각
제 블로그에 와주셔서 감사합니다! 다들 오늘 하루도 좋은 일 있으시길~~
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!