🗂️ AI

[AICE ASSOCIATE] select_dtypes, 특정 데이터 타입 선택

PM 져니 2024. 9. 9. 10:05

aggregate([np.mean, np.max]), TypeError: agg function failed [how->mean,dtype->object], 'select_dtypes'로 해결

 

# aggregate 메소드 이용하여 groupby 후 평균값과 최댓값 확인하기 
flight.set_index(['airline', 'arrival_time']).groupby(level=[0,1]).aggregate([np.mean,np.max])

 

aggreagate 메소드를 이용하여 데이터프레임의 평균값과 최댓값을 한 번에 확인하는 코드를 실행했을 때 아래와 같은 오류가 발생했다. 

 

TypeError: agg function failed [how->mean,dtype->object]
 

[AICE ASSOCIATE] mean() 함수, TypeError: agg function failed [how->mean,dtype->object], 'numeric_only=True'로 해결

mean() 함수, TypeError: agg function failed [how->mean,dtype->object], 'numeric_only=True'로 해결 # 평균값 확인하기airline_group.mean()# 특정 칼럼 값만 확인하기airline_group.mean()[['price']]# groupby를 활용하여 다중

urjourney.co.kr

 

mean() 함수를 쓸 때 같은 오류가 나서 이때는 numeric_only=True를 사용하여 해결했는데, 여기서는 사용할 수가 없어서 다시 방법을 찾아봤다. 바로 수치형 데이터 타입을 가진 행들을 선택하는 코드를 추가해 주면 된다.

 

# 수치형 데이터타입을 가진 칼럼만 선택
flight.select_dtypes(include=[np.number]).columns

 

select_dtypes 메소드는 특정 데이터 타입에 맞는 열을 선택하는 기능을 한다. select_dtypes(include=None, exclude=None) 형태를 가지며, include는 선택하고자 하는 데이터타입을 지정하고 exclude는 제외할 데이터타입을 지정하여 이에 맞는 칼럼을 데이터프레임 형태로 반환한다.

 

수치형 데이터만 포함하기 위해서는 np.number 또는 'number'를 사용하면 된다.

 

.columns를 통해 선택된 행의 이름을 반환한다.

 

이 코드를 flight.set_index(['airline', 'arrival_time']) 뒤에 [] 안에 넣어서 붙여주면 인덱스가 설정된 데이터프레임에서 수치형 데이터를 가진 선택된 수치형 데이터를 가진 행 만을 선택하게 된다. groupby[level=[0,1]) 뒤에 붙여줘도 상관없다. 집계 함수를 사용하는 aggregate 앞에만 위치하면 된다.

 

# aggregate 메소드 이용하여 groupby 후 평균값과 최댓값 확인하기 
flight.set_index(['airline', 'arrival_time'])[flight.select_dtypes(include=[np.number]).columns].groupby(level=[0,1]).aggregate([np.mean, np.max])
flight.set_index(['airline', 'arrival_time']).groupby(level=[0,1])[flight.select_dtypes(include=[np.number]).columns].aggregate([np.mean, np.max])

 

이대로 실행하면 아래와 같은 코드가 뜨게 되는데,

C:\Users\dmswn\AppData\Local\Temp\ipykernel_15432\1798954567.py:4: FutureWarning: The provided callable <function mean at 0x000002131C167560> is currently using SeriesGroupBy.mean. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string "mean" instead.
  flight.set_index(['airline', 'arrival_time']).groupby(level=[0,1])[flight.select_dtypes(include=[np.number]).columns].aggregate([np.mean, np.max])
C:\Users\dmswn\AppData\Local\Temp\ipykernel_15432\1798954567.py:4: FutureWarning: The provided callable <function max at 0x000002131C166B60> is currently using SeriesGroupBy.max. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string "max" instead.
  flight.set_index(['airline', 'arrival_time']).groupby(level=[0,1])[flight.select_dtypes(include=[np.number]).columns].aggregate([np.mean, np.max])
C:\Users\dmswn\AppData\Local\Temp\ipykernel_15432\1798954567.py:4: FutureWarning: The provided callable <function mean at 0x000002131C167560> is currently using SeriesGroupBy.mean. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string "mean" instead.
  flight.set_index(['airline', 'arrival_time']).groupby(level=[0,1])[flight.select_dtypes(include=[np.number]).columns].aggregate([np.mean, np.max])

 

이거는 aggregate([np.mean, np.max])를 aggregate(['mean', 'max'])로 바꿔주면 해결된다. 향후 버전에서 np.mean 형태가 아닌 'mean' 형태로 사용을 하게 되어서 그렇다고 한다.

 

 

 

 

참고자료

위키독스, 05-02. dtype기반 열 선택 (select_dtyps)


*본 포스팅은 《시나공 AI 능력시험 AICE ASSOCIATE 편》교재를 공부하며 작성하였습니다.