딥상어동의 딥한 생각

심심해서만들어보는함수 - Pandas 인덱싱 메서드로 컬럼 순서 변경하기

by 딥상어동의 딥한생각

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("잘못된 메서드를 입력하셨습니다.")

블로그의 정보

딥상어동의 딥한생각

딥상어동의 딥한생각

활동하기