> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined-6/pandas.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# Pandas 탐색적 자료 분석

```notebook-python
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data_dir = "dir"
```

## 개요

## 1. CSV자료 읽기

* &#x20;CSV (Comma Separated Values) 파일 읽기. 쉼표나 다른 구분자로 항목이 나뉜 텍스트 데이터
* `pd.read_csv()`
  * `header` : 컬럼(열) 이름으로 사용할 행의 번호 (0부터 시작), header=None
  * `index_col` : 행의 이름(인덱스)으로 사용할 컬럼의 번호, index\_col=0
  * `sep`: 데이터 항목을 구분하는 구분자 (str 자료형). 기본값은 쉼표(,)
  * `skiprows`: 파일의 맨 위부터 지정한 개수만큼의 행을 건너뛰고 읽음, skiprows=3 (처음 3줄 건너뛰기)
  * `nrows`: 파일에서 읽어올 행의 개수. 대용량 파일에서 일부만 테스트로 불러올 때 유용, nrows=1000 (처음 1000줄만 읽기)

```python
## csv 전체
titanic_path = os.path.join(data_dir, "titanic.csv")
titanic = pd.read_csv(titanic_path , header = 0, index_col = 0, sep = "," , skiprows=0, nrows=3)
display("titanic = ", titanic.head())
print('titanic shape = ', titanic.shape)
```

## 2. Excel  자료 읽기

* `pd.read_excel()`: Excel (.xlsx, .xls) 파일 읽기
  * `header` : 컬럼(열) 이름으로 사용할 행의 번호 (0부터 시작), header=None
  * `index_col` : 행의 이름(인덱스)으로 사용할 컬럼의 번호, index\_col=0
  * `skiprows`: 파일의 맨 위부터 지정한 개수만큼의 행을 건너뛰고 읽음, skiprows=3 (처음 3줄 건너뛰기)
  * `nrows`: 파일에서 읽어올 행의 개수. 대용량 파일에서 일부만 테스트로 불러올 때 유용, nrows=1000 (처음 1000줄만 읽기)
* `mtcars` 자료
  * 1974년 자동차 트렌드에서 발췌한 32가지 차종의 연비, 마력, 무게 등 다양한 사양 정보를 포함
  * 상관 분석, 회귀 분석 등 다양한 통계 기법을 적용하는 예시 자료로 활용

```python
mtcars_path = os.path.join(data_dir, "mtcars.xlsx")
mtcars = pd.read_excel(mtcars_path, header= 0, index_col= None)
display("mtcars = ", mtcars.head())

## CSV 자료읽기 문제
##아래와 같은 결과가 나오도록 지정된 경로에 있는 csv 파일을 읽어 보시오
'''
csv_filepath = "../data/cars.csv"
print(cars)
출력결과:

    speed	dist
1	4	2
2	4	10
3	7	4
4	7	22
5	8	16
6	9	10
7	10	18
8	10	26
9	10	34
10	11	17
'''

csv_filepath =  os.path.join(data_dir, "cars.csv")
cars = pd.read_csv(csv_filepath, skiprows = 3, index_col = 0)

print(cars.head(10))

## EXCEL자료읽기 무제
'''
excel_filepath = "../data/stock price.xlsx"
print(stock)
출력결과:

                id          value   price
stock_name
한미약품        128940   59385.666667  421000
CJ E&M      130960   58540.666667   98900
엔에스쇼핑       138250   14558.666667   13200
이마트         139480  239230.833333  254500
녹십자엠에스      142280     468.833333   10200
삼양사         145990   82750.000000   82000
종근당         185750   40293.666667  100500
쿠쿠홀딩스       192400  179204.666667  177500
툴젠          199800   -2514.333333  115400
모두투어리츠      204210    3093.333333    3475
'''

excel_filepath = os.path.join(data_dir, "stock price.xlsx")
stock = pd.read_excel(excel_filepath, index_col="stock_name")

print(stock)
```

## 3.  Pandas DataFrame 다루기

### **1) 데이터 탐색및 확인**

* `df.head()`: DataFrame} 상위 5개 행을 반환, df.head(10)(상위 10개 행 반환)
* `df.tail()`: DataFrame의 하위 5개 행을 반환,
* `df.shape`: DataFrame의 크기를 (행의 수, 열의 수) 튜플로 반환
* `df.columns`: DataFrame의 변수명을 반환
* `df.info()`: DataFrame에 대한 `전반적인 정보`를 요약해서 출력
* `df.describe()`: 숫자형 컬럼들의 기술 통계를 요약 (개수, 평균, 표준편차, 최솟값, 최댓값, 사분위수 등)
* `df.astype()`: 컬럼의 `자료형 (dtype)`을 변경, df\['Pclass'].astype('category')
  * 컴퓨터의 저장 형식과 분석에 필요한 타입이 다르기 때문에, 분석용으로 변경하기위해 사용한다.
* `df.tolist()`: DataFrame 자료를 list 자료로 변경
* `df.dropna()`: `NaN` 값을 제거

```python
titanic = pd.read_csv(titanic_path)
print("titanic type = ", type(titanic))

display(titanic.head(10))
display(titanic.tail())

rows, cols = titanic.shape
print("titanic 총 행 = ", rows)
print("titanic 총 열 = ", cols)

col_names = titanic.columns
display("titanic.columns = ", col_names)

display(titanic.info())
# 연속형
#  - 비율 : 키, 몸뭄게 , 0,1,2등늘어나는값
#  - 구간 : 온도
# 범주형(int값들을 category를 활용하여 범주형으로 바꿔주는게 정상)범주형 값을 int로 두면 분석에 문제가 생김.
#  - 명목형 : 남녀(0,1), 생존여부(0,1)
#  - 순서형 : pclass같은것. 순서가 정해진 값.

# 컴퓨터의 저장형식과 분석에 필요한 타입은 다름.

## 데이터 타입 변경 전
display(titanic.describe())

## 데이터 타입 변경
# category타입은 커스텀타입인가?
titanic["PassengerId"] = titanic["passengerId"].astype("category")
titanic["Survived"] = titanic["survived"].astype("category")
titanic["Pclass"] = titanic["pclass"].astype("category")

display(titanic.info())

##<데이터 타입 수정하기 문제>
##mtcars데이터를 읽고 mtcars.describe()를 수행하고자 할 때 출력결과가 아래와 같도록 데이터의 타입을 적절하게 수정하시오

[1] mpg: float 연비 (Miles per Gallon, 마일당 갤런). 자동차의 연료 효율성.
[2] cyl: int 실린더 개수 (Number of cylinders). 엔진의 실린더 수.
[3] disp: float 배기량 (Displacement in cu.in.), 엔진의 크기.
[4] hp: int 마력 (Gross horsepower). 엔진의 힘.
[5] drat: float 후륜 액슬 비율 (Rear axle ratio). 차량의 기어비 관련 수치.
[6] wt: float 차량 무게 (Weight, 1000 lbs 단위).
[7] qsec: float 1/4 마일 도달 시간 (1/4 mile time). 차량의 가속 능력을 나타내는 지표.
[8] vs: int 엔진 형태 (Engine Type). $\text{0}$은 $\text{V}$형 엔진, $\text{1}$은 직선형 엔진 ($\text{straight}$ engine)을 의미합니다.
[9] am: int 변속기 종류 (Transmission). $\text{0}$은 자동 변속기 ($\text{automatic}$), $\text{1}$은 수동 변속기 ($\text{manual}$)를 의미합니다.
[10]gear: int 전진 기어 개수 (Number of forward gears).
[11]carb: int 카뷰레터 개수 (Number of carburetors).

##
# mtcars.describe()

# [츨력 결과]
'''
        mpg	        cyl	        disp	    hp	        drat	    wt	        qsec	    gear	    carb
count	32.000000	32.000000	32.000000	32.000000	32.000000	32.000000	32.000000	32.000000	32.0000
mean	20.090625	6.187500	230.721875	146.687500	3.596563	3.217250	17.848750	3.687500	2.8125
std	6.026948	1.785922	123.938694	68.562868	0.534679	0.978457	1.786943	0.737804	1.6152
min	10.400000	4.000000	71.100000	52.000000	2.760000	1.513000	14.500000	3.000000	1.0000
25%	15.425000	4.000000	120.825000	96.500000	3.080000	2.581250	16.892500	3.000000	2.0000
50%	19.200000	6.000000	196.300000	123.000000	3.695000	3.325000	17.710000	4.000000	2.0000
75%	22.800000	8.000000	326.000000	180.000000	3.920000	3.610000	18.900000	4.000000	4.0000
max	33.900000	8.000000	472.000000	335.000000	4.930000	5.424000	22.900000	5.000000	8.0000
'''
mtcars_path = os.path.join(data_dir, "mtcars.xlsx")
mtcars = pd.read_excel(mtcars_path)

mtcars["vs"] = mtcars["vs"].astype('category')
mtcars["am"] = mtcars["am"].astype('category')


mtcars.describe()
```

### **2) 데이터 접근 및 선택**

* `df["column"]`: 특정 컬럼(Series 형태)을 선택, df\['Age']
* `df[["column1", "column2"]]`: 여러 개의 컬럼(DataFrame 형태)을 선택, df\[\['Name', 'Fare']]
* `df.loc[]`: 레이블 (행 인덱스 이름, 컬럼 이름)을 사용하여 행과 열을 선택, df.loc\[0, 'Name'] (0번 인덱스의 Name 값)
* `df.iloc[]`: 정수 위치 (행 인덱스 번호, 열 인덱스 번호) 를 사용하여 행과 열을 선택

```python
# PassengerId 선택
passengers = titanic["passengerId"]
display("passengers = ", passengers)

# PassengerId, Survived 선택
passengers_survived = titanic[["passengerId", "survived"]]
display('titanic[["passengerId", "survived"]] = ', passengers_survived)
titanic.head()

# PassengerId, Survived, Age 선택
passengers_survived_age = titanic[["passengerId", "survived", "age"]]
display('titanic[["PassengerId", "Survived", "Age"]] = ', passengers_survived_age)

# loc 선택
titanic_loc1 = titanic.loc[0, "survived"]
print('titanic.loc[0, "Survived"] = ', titanic_loc1)

titanic_loc2 = titanic.loc[0:10, ["survived", "age", "pclass"]]
display('titanic.loc[0:10, ["Survived", "Age", "Pclass"]] = ', titanic_loc2)

titanic_loc3 = titanic.loc[:, "survived":"parch"]
display('titanic.loc[:, "Survived":"Parch"] = ', titanic_loc3)

# iloc를 이용한 선택
titanic_iloc1 = titanic.iloc[:10, :3]
display("titanic_1.iloc[:10, :3] = ", titanic_iloc1)

titanic_iloc2 = titanic.iloc[10:20, [1, 2, 4, 5, 6, 7]]
display("titanic.iloc[10:20, [1, 2, 4, 5, 6, 7]] = ", titanic_iloc2)

## 자료 접근 문제 1
## DataFrame loc 인덱싱을 이용하여 아래의 출력 결과가 나오도록 데이터를 읽어 보시오

'''
print(titanic_loc_ex)

Survived Sex Age Pclass
0	0	male	22.0	3
1	1	female	38.0	1
2	1	female	26.0	3
3	1	female	35.0	1
4	0	male	35.0	3
5	0	male	NaN	    3
6	0	male	54.0	1
7	0	male	2.0	    3
8	1	female	27.0	3
9	1	female	14.0	2
10	1	female	4.0	    3
'''

titanic_loc_ex = titanic.loc[0:10, ["survived", "sex", "age", "pclass"]]
print(titanic_loc_ex)

## 자료접근문제 2
## DataFrame iloc 인덱싱을 이용하여 아래의 출력 결과가 나오도록 데이터를 읽어 보시오
'''
print(titanic_iloc_ex)

PassengerId	Survived	Pclass	Name
10	11	1	3	Sandstrom, Miss. Marguerite Rut
11	12	1	1	Bonnell, Miss. Elizabeth
12	13	0	3	Saundercock, Mr. William Henry
13	14	0	3	Andersson, Mr. Anders Johan
14	15	0	3	Vestrom, Miss. Hulda Amanda Adolfina
15	16	1	2	Hewlett, Mrs. (Mary D Kingcome)
16	17	0	3	Rice, Master. Eugene
17	18	1	2	Williams, Mr. Charles Eugene
18	19	0	3	Vander Planke, Mrs. Julius (Emelia Maria Vande...
19	20	1	3	Masselmani, Mrs. Fatima
20	21	0	2	Fynney, Mr. Joseph

'''

titanic_iloc_ex = titanic.iloc[10:21, :4]
display(titanic_iloc_ex)

```

## 4. 데이터 기초 통계량

* 탐색적 자료 분석 (EDA)?
*

```
<figure><img src="/files/rhNavUKRxmAhwoPBmwxF" alt=""><figcaption></figcaption></figure>
```

* **중심의 위치측도**
  * `표본평균 (Sample Mean)`
    * 중심을 나타내는 측도 중에서 가장 많이 사용되는 방법
    * 자료의 무게 중심을 나타냄
    * 자료의 이상치 (Outlier)에 영향을 많이 받음 (Trimmed mean)
  * `중앙값 (Median)`

    * 전체 관측값을 크기 순으로 나열한 했을 때 중앙에 위치한 값
    * 자료의 갯수(n) 이 홀수이면 $$n+12$$ 번째 관측값
    * 자료의 갯수(n) 이 짝수이면 $$n2$$과 $$n+12$$ 번째 관측값의 평균값
    * 자료의 이상치 (Outlier)에 영향을 적게 받음
    * 야구선수의 연봉표같은걸 보면, 평균은 높고, 중앙값은 작은 형태를 띄고있음.
    *

    ```
    <figure><img src="/files/PJ4omLuOuIbSQhsNkzgN" alt=""><figcaption></figcaption></figure>
    ```
* `df.mean()`: DataFrame/Series 의 평균
* `df.median()`: DataFrame/Series 의 중앙값

```python
## 평균 운임료
fare_mean = titanic["Fare"].mean()
print("fare_mean = ", fare_mean)

## 운임료 중앙값
fare_median = titanic["Fare"].median()
print("fare_median = ", fare_median)
```

```python
## For 구문을 이용한 titanic 요금 분산
# 직접 구한것과, df함수를 이용한 값간의 차이는 어디서 나오는것?

titanic_fare = titanic["Fare"]
# print("titanic_fare = ", titanic_fare)

fare_sum = 0
for i in titanic_fare:
    fare_sum = fare_sum + i

fare_mean = fare_sum/891

fare_var = 0

for i in titanic_fare:
    fare_var = fare_var + (i - fare_mean)**2

fare_var = fare_var/891

print("Variance of fare = ", fare_var)

```

* **분산과 표준편차**

  * 자료가 중심으로 부터 얼마나 퍼져있는 지를 표현 수치
  *

  ```
  <figure><img src="/files/CuHCFiwCcg1k5MzdZTFK" alt=""><figcaption></figcaption></figure>
  ```

  * 범위(Range): 최댓값 - 최솟값
  * 무슨 메서드가 있나 확인 필요. var, std, range?

```python
## For 구문을 이용한 titanic 요금 분산
# 직접 구한것과, df함수를 이용한 값간의 차이는 어디서 나오는것?

titanic_fare = titanic["Fare"]
# print("titanic_fare = ", titanic_fare)

fare_sum = 0
for i in titanic_fare:
    fare_sum = fare_sum + i

fare_mean = fare_sum/891

fare_var = 0

for i in titanic_fare:
    fare_var = fare_var + (i - fare_mean)**2

fare_var = fare_var/891

print("Variance of fare = ", fare_var)

## numpy sqrt를이용한 titanic 요금 표준편차
fare_std = np.sqrt(fare_var)
print("std of fare = ", fare_std)

## titanic 요금 분위 범위
fare_range = titanic_fare.max() - titanic_fare.min()
print("range of fare = ", fare_range)

## DataFrame method를 이용한 분산, 표준편차, 범위
titanic_fare = titanic["Fare"]

titanic_fare_var = titanic_fare.var()
titanic_fare_std = titanic_fare.std()

print("titanic_fare.var() = ", titanic_fare_var)
print("titanic_fare.std() = ", titanic_fare_std)
## 범위?

## 결과 요약
summary_stat = {
    "mean": fare_mean,
    "median": fare_median,
    "variance": fare_var,
    "std": fare_std,
    "range": fare_range
}

display(summary_stat)

df_summary = pd.DataFrame([summary_stat], index=['Fare'])
display("titanic 요금 통계량 = ", df_summary.round(3))
```

## 5. 데이터 정제 및 전처리

* **정제 및 전처리 메서드**:
  * `.isnull()`: $$DataFrame$$의 각 요소가 **결측치**($$NaN$$)인지 여부를 불리언 $$DataFrame$$으로 반환
  * `.dropna()`: 결측치가 있는 행 또는 열을 제거
  * `.fillna()`: 결측치를 특정 값으로 채움
  * `.drop()`: 행 또는 열을 제거
  * `.rename()`: 인덱스 또는 열 이름을 변경
  * `.value_counts()`: 특정 열의 고유값별 개수 (빈도)를 반환
  * `.unique()`: 특정 열의 고유값 목록을 배열로 반환

```python
titanic_path = os.path.join(data_dir, "titanic.csv")
titanic = pd.read_csv(titanic_path, index_col="PassengerId")
titanic.head()

## 1. df.isnull()
## - 결측치 확인 메서드
## - 각 요소가 NaN이라면 True/False로 반환
print("\n--- .isnull()을 이용한 결측치 확인 ---")
print(titanic.isnull().head(10))

print("\n--- .isnull().sum(axis = 0)을 이용한 결측치 확인 ---")
print(titanic.isnull().sum(axis = 0))

## 2. df.fillna()
## - 결측치를 특정 값으로 채우는 메서드
# Age 열의 NaN 값을 0으로 채움
titanic_fill0 = titanic['Age'].fillna(0)
print(titanic_fill0.head(10))

# Age의 평균 계산
# 0보다 평균으로 넣는게 좋음.
mean_age = titanic['Age'].mean()

# Age 열의 NaN 값을 평균값으로 채움
titanic['Age'] = titanic['Age'].fillna(mean_age)

print("\n--- .fillna()로 Age 결측치 채우기 ---")
print(titanic[['Age']].head(7)) # 값이 채워졌는지 확인

## 3. df.dropna()
## - 결측치 제거 메서드
## - 결측치가 잇는 행 또는 열을 제거한다.
# Cabin 열에 NaN이 있는 행 제거 (원본을 건드리지 않기 위해 새로운 변수에 저장)
titanic_dropped_cabin = titanic.dropna(subset=['Cabin'])

print("\n--- dropna()로 Cabin 결측 행 제거 후 크기 확인 ---")
print(f"원본 데이터 행 수: {len(titanic)}")
print(f"Cabin 결측치 제거 후 행 수: {len(titanic_dropped_cabin)}")

# Titanic에서 NaN이 있는 모든 행 제거 (원본을 건드리지 않기 위해 새로운 변수에 저장)
titanic_dropped = titanic.dropna()

print("\n--- dropna()로 Cabin 결측 행 제거 후 크기 확인 ---")
print(f"원본 데이터 행 수: {len(titanic)}")
print(f"Cabin 결측치 제거 후 행 수: {len(titanic_dropped)}")
display(titanic_dropped.head(10))

## 5. df.drop()
## - 특정 열 제거 메서드
## - 데이터 분석 과정에서 불필요한 열 제거.
# PassengerId 열과 Name 열 제거 (axis=1은 열을 의미하며, 원본 titanic 수정)
titanic_selected = titanic.drop(columns=[ 'Name', "Ticket", "Cabin", "Embarked"])

print("\n--- .drop()으로 불필요한 열 제거 ---")
print(titanic_selected.head(20))

## 불필요한 열 제거 문제 
## titanic_selected 자료에서 SibSp, Parch 열을 제거하고 자료를 titanic_selected_v2로 저장하고 프린트 하시오

titanic_selected_v2 = titanic_selected.drop(columns={"SibSp", "Parch"})
print("titanic_selected_v2 \n", titanic_selected_v2)

## 6. df.rename()
## - 열 이름 변경 메서드
# columns 딕셔너리를 사용하여 열 이름 변경
titanic_renamed = titanic_selected.rename(
    columns={'Survived': '생존여부'})

print("\n---.rename()으로 열 이름 변경 ---")
print(titanic_renamed.head())

## 변수명 바꾸기 문제
##titanic_selected 자료를 이용하여 **'Survived' -> '생존여부', 'Pclass' -> '객실등급', 'Sex' -> '성별', 'Age' -> '나이', 'SibSp' -> '가족친지수', 'Parch' -> '부모', 'Fare' -> '요금' **로 변경하여 titanic_renamed로 저장하시오
titanic_renamed = titanic_selected.rename(
    columns={'Survived': '생존여부',
             'Pclass': '객실등급',
             'Sex': '성별',
             'Age': '나이',
             'SibSp': '가족친지수',
             'Parch': '부모',
             'Fare': '요금'}
    )
    
## 7 df.unique()
### - 고유값 목록 확인 
# Sex 열의 고유값 확인
sex_unique = titanic['Sex'].unique()

print("\n--- unique()로 Sex 고유값 확인 ---")
print(sex_unique)

# Embarked 열의 고유값 확인
Embarked_unique = titanic['Embarked'].unique()

print("\n--- unique()로 Embarked 고유값 확인 ---")
print(Embarked_unique)

## 고유값 목록확인 문제
## titanic 자료에서 Cabin 에 대한 고유값 목록을 확인하고 프린트 하시오
titanic_unique = titanic["Cabin"].unique()
print(titanic_unique)

## 8. df.value_counts()
## 고유값별 빈도 확인 메서드
# TicketClass 열의 고유값별 개수 확인
class_counts = titanic['Pclass'].value_counts()

print("\n---.value_counts()로 TicketClass 빈도 확인 ---")
print(class_counts)

## titanic 자료에서 생존자와 사망자의 빈도수를 확인하고 프린트해 보시오
survived_count = titanic["Survived"].value_counts()
print(survived_count)
```

## 6. 데이터 조작 및 계산

* 데이터를 변형하거나 통계적 계산을 수행하는 데 사용
* **조작 및 계산 메서드**:

  * `.sort_values()`: 하나 이상의 열을 기준으로 정렬
  * `.sort_indexs()`: 하나 이상의 인덱스를 기준으로 정렬
  * `.replace()`: DataFrame 또는 $$Series$$의 특정 값을 다른 값으로 변경
  * `.groupby()`: 특정 열을 기준으로 데이터를 그룹화

{% hint style="info" %}
**< mtcars > 자료 소개**

* mtcars는 통계 소프트웨어 R에 내장된 데이터셋으로, 데이터 분석을 위한 예제 자료로 널리 사용됩니다. 이 데이터셋은 1974년 미국 잡지 '모터 트렌드 US(Motor Trend US)'에 실린 내용을 기반으로 하며, 1973\~1974년식 자동차 32대에 대한 연료 소비량 및 10가지 자동차 디자인 및 성능 측면의 정보를 포함하고 있습니다.
* mtcars 데이터셋은 32개의 관측치(자동차 모델)와 11개의 변수로 구성되어 있습니다. 각 변수는 다음과 같은 정보를 담고 있습니다.
  * `mpg`: 마일/갤런(연비). 1갤런당 주행할 수 있는 마일 수
  * `cyl`: 실린더 수
  * `disp`: 배기량 (입방인치)
  * `hp`: 총 마력
  * `drat`: 후륜 차축 비율
  * `wt`: 중량 (1000파운드)
  * `qsec`: 1/4마일 도달 시간 (가속도 측정)
  * `vs`: 엔진 유형 (0 = V-형, 1 = 직렬형)
  * `am`: 변속기 유형 (0 = 자동, 1 = 수동)
  * `gear`: 전진 기어 수
  * `carb`: 기화기 수
    {% endhint %}

```python
mtcars_path = os.path.join(data_dir, "mtcars.xlsx")
mtcars = pd.read_excel(mtcars_path, index_col=0)
mtcars.head()

## 1. df..sort_values()
## -  열 값 기준으로 정렬 
# mpg (연비) 기준으로 내림차순 정렬 (ascending=False)
sorted_by_mpg = mtcars.sort_values(by='mpg', ascending=False)

print("\n--- .sort_values() (mpg 내림차순 정렬) ---")
print(sorted_by_mpg.head())

# cyl, mpg (연비) 기준으로 내림차순 정렬 (ascending=False)
sorted_by_mpg = mtcars.sort_values(by=['cyl','mpg'], ascending=False)

print("\n--- .sort_values() (['cyl','mpg'] 내림차순 정렬) ---")
print(sorted_by_mpg.head())


### 2. df.sort_index()
## - 인덱스 기준 정렬
# 인덱스 (차량 이름) 기준으로 오름차순 정렬 (기본값: ascending=True)
sorted_by_index = mtcars.sort_index()

print("\n--- .sort_index() (차량 이름 오름차순 정렬) ---")
print(sorted_by_index.head(10))

## 정렬문제
##mtcars 자료를 무게 (wt)에 따라서 오름차순으로 정리하고 자료를 mtcars_wt로 저장한 후 10 ~ 20 열에 있는 자료만 프린트 하시오

# < 풀이 >
mtcars_wt = mtcars.sort_values("wt", ascending=True)
mtcars_wt.head()

## 3. df.replace()
## - 열값 대체
# gear 열의 숫자 값을 문자열로 대체
# 3 -> 'Low Gear', 4 -> 'Mid Gear', 5 -> 'High Gear', 6 -> 'Sport Gear'
mtcars['gear_label'] = mtcars['gear'].replace({
    3: 'Low Gear',
    4: 'Mid Gear',
    5: 'High Gear',
    6: 'Sport Gear'
})

print("\n--- .replace() (gear 값 대체) ---")
print(mtcars[['gear', 'gear_label']].head(7))

## 문제
## mtcars 자료에서 am 열의 값을 0 -> 수동, 1 -> 자동 으로 변경하고 프린트 하시오
mtcars["am_rename"]= mtcars["am"].replace({0:"자동", 1:"수동"})
print(mtcars.head())

## 4. df..groupby()
## - 데이터 그룹화 및 집계
# 'cyl' (실린더 개수) 기준으로 그룹화하고 'mpg'의 평균 계산
grouped_mpg = mtcars.groupby('cyl')['mpg'].mean()

print("\n--- .groupby() (실린더별 평균 mpg) ---")
print(grouped_mpg)

# 'cyl' (실린더 개수) 기준으로 그룹화하고 'mpg'의 중앙값 계산
grouped_mpg = mtcars.groupby('cyl')['mpg'].median()

print("\n--- .groupby() (실린더별 중앙값 mpg) ---")
print(grouped_mpg)

# 'cyl' (실린더 개수) 기준으로 그룹화하고 'mpg'의 표준편차를 계산
grouped_mpg = mtcars.groupby('cyl')['mpg'].std()

print("\n--- .groupby() (실린더별 표준편차 mpg) ---")
print(grouped_mpg)

# 'am', 'cyl' (실린더 개수) 기준으로 그룹화하고 'mpg'의 평균 계산
grouped_mpg = mtcars.groupby(['am', 'cyl'])['mpg'].mean()

print("\n--- .groupby() (실린더별 평균 mpg) ---")
print(grouped_mpg)

## 문제
## mtcars 자료에서 엔진유형 (vs) 에 따른 연비 (mpg) 의 평균값과 표준편차를 각 각 구하고 프린트 하시오
# < 풀이 >
print("mean by am = ")
print(mtcars.groupby("am")["mpg"].mean())

print("\n std by am = ")
print(mtcars.groupby("am")["mpg"].std())

```

## 7. 데이터 인덱싱

* **데이터 인덱싱 메서드**:
  * `.reset_index()`: 현재 인덱스를 열로 변환하고, 새로운 기본 정수 인덱스를 설정
  * `.set_index()`: $$DataFrame$$의 특정 열을 새로운 인덱스로 설정
  * `.rank()`: 데이터의 순위를 매김

```python
## 1. df.reset_index()
##  - 인덱스를 열로 변환하는 메서드
##  - 새로운 기본 정수 인덱스로 변경된다.

# 현재 인덱스(차량 이름)를 'CarName'이라는 열로 변환
mtcars_reset = mtcars.reset_index(names=['CarName'], drop = False)

print("\n--- .reset_index() 적용 결과 ---")
print(mtcars_reset.head())

## 2. df.set_index()
## - 특정열을 인덱스로 설정하는 메서드
# 'CarName' 열을 제거하고 'cyl' 열을 새로운 인덱스로 설정
mtcars_set = mtcars_reset.set_index('cyl')

print("\n--- set_index() 적용 결과 (cyl 기준) ---")
print(mtcars_set)
print(f"\n새로운 인덱스 이름: {mtcars_set.index.name}")

## 문제
## 위 예제에서 구해던 mtcars_set을 이용하여 0 부터 시작하는 정수형 인덱스로 바꾸고 
## 기존의 인덱스 cyl을 컬럼으로 복귀시키고 자료를 mtcars_reset으로 저장하고 출력해 보시오

# < 풀이 >
mtcars_reset = mtcars_set.reset_index("cyl")
display(mtcars_reset.head())

## 3. df.rank()
## - 데이터 순위 매기기
# hp가 낮은 순서대로 순위를 매김 (오름차순). 동점은 평균 순위를 부여.
# 62hp가 가장 낮으므로 1위
mtcars['hp_rank_asc'] = mtcars['hp'].rank(ascending=True, method='average')

print("\n--- 3.1. .rank() (hp 오름차순 순위) ---")
print(mtcars[['hp', 'hp_rank_asc']].sort_values('hp', ascending=False).head())

# hp가 높은 순서대로 순위를 매김 (내림차순). 동점은 낮은 순위(min)를 부여.
# 245hp가 가장 높으므로 1위
mtcars['hp_rank_desc'] = mtcars['hp'].rank(ascending=False, method='min')

print("\n--- .rank() (hp 내림차순 순위, method='min') ---")
print(mtcars[['hp', 'hp_rank_desc']].sort_values('hp', ascending=False).head())

## 문제
## mtcars 자료를 이용하여 연비 (mpg) 에 따라서 가장 높은 값이 1 갖도록 만들고 
## 순위자료를 mtcars 에 ranked 라는 열이름으로 저장하고 출력해 보시오
mtcars["ranked"] = mtcars["mpg"].rank(ascending=False)
display(mtcars)
```
