1. 데이터 불러오기
# seaborn의 mpg 데이터셋 로드
mpg_df = pl.from_pandas(sns.load_dataset('mpg'))
mpg_df
# seaborn의 mpg 데이터셋 로드
mpg_df = pl.from_pandas(sns.load_dataset('mpg'))
mpg_df
2. 데이터 정보 확인
print("데이터 기본 정보:")
print(mpg_df.glimpse())
print(mpg_df.describe())
print("데이터 기본 정보:")
print(mpg_df.glimpse())
print(mpg_df.describe())
데이터 기본 정보:
Rows: 398
Columns: 9
$ mpg <f64> 18.0, 15.0, 18.0, 16.0, 17.0, 15.0, 14.0, 14.0, 14.0, 15.0
$ cylinders <i64> 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
$ displacement <f64> 307.0, 350.0, 318.0, 304.0, 302.0, 429.0, 454.0, 440.0, 455.0, 390.0
$ horsepower <f64> 130.0, 165.0, 150.0, 150.0, 140.0, 198.0, 220.0, 215.0, 225.0, 190.0
$ weight <i64> 3504, 3693, 3436, 3433, 3449, 4341, 4354, 4312, 4425, 3850
$ acceleration <f64> 12.0, 11.5, 11.0, 12.0, 10.5, 10.0, 9.0, 8.5, 10.0, 8.5
$ model_year <i64> 70, 70, 70, 70, 70, 70, 70, 70, 70, 70
$ origin <str> 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa'
$ name <str> 'chevrolet chevelle malibu', 'buick skylark 320', 'plymouth satellite', 'amc rebel sst', 'ford torino', 'ford galaxie 500', 'chevrolet impala', 'plymouth fury iii', 'pontiac catalina', 'amc ambassador dpl'
None
shape: (9, 10)
┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬─────────┐
│ statist ┆ mpg ┆ cylinde ┆ displac ┆ horsepo ┆ weight ┆ acceler ┆ model_y ┆ origin ┆ name │
│ ic ┆ --- ┆ rs ┆ ement ┆ wer ┆ --- ┆ ation ┆ ear ┆ --- ┆ --- │
│ --- ┆ f64 ┆ --- ┆ --- ┆ --- ┆ f64 ┆ --- ┆ --- ┆ str ┆ str │
│ str ┆ ┆ f64 ┆ f64 ┆ f64 ┆ ┆ f64 ┆ f64 ┆ ┆ │
╞═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪════════╪═════════╡
│ count ┆ 398.0 ┆ 398.0 ┆ 398.0 ┆ 392.0 ┆ 398.0 ┆ 398.0 ┆ 398.0 ┆ 398 ┆ 398 │
│ null_co ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 6.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0 ┆ 0 │
│ unt ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ │
│ mean ┆ 23.5145 ┆ 5.45477 ┆ 193.425 ┆ 104.469 ┆ 2970.42 ┆ 15.5680 ┆ 76.0100 ┆ null ┆ null │
│ ┆ 73 ┆ 4 ┆ 879 ┆ 388 ┆ 4623 ┆ 9 ┆ 5 ┆ ┆ │
│ std ┆ 7.81598 ┆ 1.70100 ┆ 104.269 ┆ 38.4911 ┆ 846.841 ┆ 2.75768 ┆ 3.69762 ┆ null ┆ null │
│ ┆ 4 ┆ 4 ┆ 838 ┆ 6 ┆ 774 ┆ 9 ┆ 7 ┆ ┆ │
│ min ┆ 9.0 ┆ 3.0 ┆ 68.0 ┆ 46.0 ┆ 1613.0 ┆ 8.0 ┆ 70.0 ┆ europe ┆ amc amb │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ assador │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ brougha │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ m │
│ 25% ┆ 17.5 ┆ 4.0 ┆ 104.0 ┆ 75.0 ┆ 2223.0 ┆ 13.8 ┆ 73.0 ┆ null ┆ null │
│ 50% ┆ 23.0 ┆ 4.0 ┆ 151.0 ┆ 94.0 ┆ 2807.0 ┆ 15.5 ┆ 76.0 ┆ null ┆ null │
│ 75% ┆ 29.0 ┆ 8.0 ┆ 262.0 ┆ 125.0 ┆ 3609.0 ┆ 17.2 ┆ 79.0 ┆ null ┆ null │
│ max ┆ 46.6 ┆ 8.0 ┆ 455.0 ┆ 230.0 ┆ 5140.0 ┆ 24.8 ┆ 82.0 ┆ usa ┆ vw │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ rabbit │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ custom │
└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴─────────┘
데이터 기본 정보:
Rows: 398
Columns: 9
$ mpg <f64> 18.0, 15.0, 18.0, 16.0, 17.0, 15.0, 14.0, 14.0, 14.0, 15.0
$ cylinders <i64> 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
$ displacement <f64> 307.0, 350.0, 318.0, 304.0, 302.0, 429.0, 454.0, 440.0, 455.0, 390.0
$ horsepower <f64> 130.0, 165.0, 150.0, 150.0, 140.0, 198.0, 220.0, 215.0, 225.0, 190.0
$ weight <i64> 3504, 3693, 3436, 3433, 3449, 4341, 4354, 4312, 4425, 3850
$ acceleration <f64> 12.0, 11.5, 11.0, 12.0, 10.5, 10.0, 9.0, 8.5, 10.0, 8.5
$ model_year <i64> 70, 70, 70, 70, 70, 70, 70, 70, 70, 70
$ origin <str> 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa', 'usa'
$ name <str> 'chevrolet chevelle malibu', 'buick skylark 320', 'plymouth satellite', 'amc rebel sst', 'ford torino', 'ford galaxie 500', 'chevrolet impala', 'plymouth fury iii', 'pontiac catalina', 'amc ambassador dpl'
None
shape: (9, 10)
┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬─────────┐
│ statist ┆ mpg ┆ cylinde ┆ displac ┆ horsepo ┆ weight ┆ acceler ┆ model_y ┆ origin ┆ name │
│ ic ┆ --- ┆ rs ┆ ement ┆ wer ┆ --- ┆ ation ┆ ear ┆ --- ┆ --- │
│ --- ┆ f64 ┆ --- ┆ --- ┆ --- ┆ f64 ┆ --- ┆ --- ┆ str ┆ str │
│ str ┆ ┆ f64 ┆ f64 ┆ f64 ┆ ┆ f64 ┆ f64 ┆ ┆ │
╞═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪═════════╪════════╪═════════╡
│ count ┆ 398.0 ┆ 398.0 ┆ 398.0 ┆ 392.0 ┆ 398.0 ┆ 398.0 ┆ 398.0 ┆ 398 ┆ 398 │
│ null_co ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 6.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0 ┆ 0 │
│ unt ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ │
│ mean ┆ 23.5145 ┆ 5.45477 ┆ 193.425 ┆ 104.469 ┆ 2970.42 ┆ 15.5680 ┆ 76.0100 ┆ null ┆ null │
│ ┆ 73 ┆ 4 ┆ 879 ┆ 388 ┆ 4623 ┆ 9 ┆ 5 ┆ ┆ │
│ std ┆ 7.81598 ┆ 1.70100 ┆ 104.269 ┆ 38.4911 ┆ 846.841 ┆ 2.75768 ┆ 3.69762 ┆ null ┆ null │
│ ┆ 4 ┆ 4 ┆ 838 ┆ 6 ┆ 774 ┆ 9 ┆ 7 ┆ ┆ │
│ min ┆ 9.0 ┆ 3.0 ┆ 68.0 ┆ 46.0 ┆ 1613.0 ┆ 8.0 ┆ 70.0 ┆ europe ┆ amc amb │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ assador │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ brougha │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ m │
│ 25% ┆ 17.5 ┆ 4.0 ┆ 104.0 ┆ 75.0 ┆ 2223.0 ┆ 13.8 ┆ 73.0 ┆ null ┆ null │
│ 50% ┆ 23.0 ┆ 4.0 ┆ 151.0 ┆ 94.0 ┆ 2807.0 ┆ 15.5 ┆ 76.0 ┆ null ┆ null │
│ 75% ┆ 29.0 ┆ 8.0 ┆ 262.0 ┆ 125.0 ┆ 3609.0 ┆ 17.2 ┆ 79.0 ┆ null ┆ null │
│ max ┆ 46.6 ┆ 8.0 ┆ 455.0 ┆ 230.0 ┆ 5140.0 ┆ 24.8 ┆ 82.0 ┆ usa ┆ vw │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ rabbit │
│ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ ┆ custom │
└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴─────────┘
print(mpg_df.shape)
print(mpg_df.shape)
3. 데이터 전처리
3.1 결측값 확인
print("결측치 개수:")
print(mpg_df.null_count())
print("결측치 개수:")
print(mpg_df.null_count())
결측치 개수:
shape: (1, 9)
┌─────┬───────────┬──────────────┬────────────┬────────┬──────────────┬────────────┬────────┬──────┐
│ mpg ┆ cylinders ┆ displacement ┆ horsepower ┆ weight ┆ acceleration ┆ model_year ┆ origin ┆ name │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 │
╞═════╪═══════════╪══════════════╪════════════╪════════╪══════════════╪════════════╪════════╪══════╡
│ 0 ┆ 0 ┆ 0 ┆ 6 ┆ 0 ┆ 0 ┆ 0 ┆ 0 ┆ 0 │
└─────┴───────────┴──────────────┴────────────┴────────┴──────────────┴────────────┴────────┴──────┘
결측치 개수:
shape: (1, 9)
┌─────┬───────────┬──────────────┬────────────┬────────┬──────────────┬────────────┬────────┬──────┐
│ mpg ┆ cylinders ┆ displacement ┆ horsepower ┆ weight ┆ acceleration ┆ model_year ┆ origin ┆ name │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 │
╞═════╪═══════════╪══════════════╪════════════╪════════╪══════════════╪════════════╪════════╪══════╡
│ 0 ┆ 0 ┆ 0 ┆ 6 ┆ 0 ┆ 0 ┆ 0 ┆ 0 ┆ 0 │
└─────┴───────────┴──────────────┴────────────┴────────┴──────────────┴────────────┴────────┴──────┘
4. 제조국가별 연비 분석
manufacturer_analysis = (
mpg_df.group_by('origin')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('weight').mean().alias('평균_중량'),
pl.count().alias('차량_수')
])
.sort('평균_연비', descending=True)
)
print("제조사별 연비 분석:")
print(manufacturer_analysis)
manufacturer_analysis = (
mpg_df.group_by('origin')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('weight').mean().alias('평균_중량'),
pl.count().alias('차량_수')
])
.sort('평균_연비', descending=True)
)
print("제조사별 연비 분석:")
print(manufacturer_analysis)
제조사별 연비 분석:
shape: (3, 5)
┌────────┬───────────┬───────────┬─────────────┬─────────┐
│ origin ┆ 평균_연비 ┆ 평균_마력 ┆ 평균_중량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════╪═══════════╪═══════════╪═════════════╪═════════╡
│ japan ┆ 30.450633 ┆ 79.835443 ┆ 2221.227848 ┆ 79 │
│ europe ┆ 27.891429 ┆ 80.558824 ┆ 2423.3 ┆ 70 │
│ usa ┆ 20.083534 ┆ 119.04898 ┆ 3361.931727 ┆ 249 │
└────────┴───────────┴───────────┴─────────────┴─────────┘
제조사별 연비 분석:
shape: (3, 5)
┌────────┬───────────┬───────────┬─────────────┬─────────┐
│ origin ┆ 평균_연비 ┆ 평균_마력 ┆ 평균_중량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════╪═══════════╪═══════════╪═════════════╪═════════╡
│ japan ┆ 30.450633 ┆ 79.835443 ┆ 2221.227848 ┆ 79 │
│ europe ┆ 27.891429 ┆ 80.558824 ┆ 2423.3 ┆ 70 │
│ usa ┆ 20.083534 ┆ 119.04898 ┆ 3361.931727 ┆ 249 │
└────────┴───────────┴───────────┴─────────────┴─────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(manufacturer_analysis))
width = 0.2
# numpy 배열로 변환
mpg = manufacturer_analysis['평균_연비'].to_numpy()
hp = manufacturer_analysis['평균_마력'].to_numpy()
weight = manufacturer_analysis['평균_중량'].to_numpy()/100 # 중량은 스케일 조정
counts = manufacturer_analysis['차량_수'].to_numpy()
# 막대 그래프 생성
fig, ax1 = plt.subplots(figsize=(12, 6))
ax2 = ax1.twinx()
# 막대 그래프: 평균 연비, 마력, 중량(스케일 조정)
bars1 = ax1.bar(x - width, mpg, width, label='평균 연비(mpg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, weight, width, label='평균 중량(×100kg)', color='salmon')
# 선 그래프: 차량 수
line = ax2.plot(x, counts, 'ko-', linewidth=2, label='차량 수', markersize=8)
# 그래프 꾸미기
plt.title('제조국가별 자동차 특성 분석', pad=20, size=15)
ax1.set_xlabel('제조국')
ax1.set_ylabel('연비/마력/중량')
ax2.set_ylabel('차량 수')
# x축 레이블 설정
plt.xticks(x, manufacturer_analysis['origin'])
# 데이터 레이블 추가
def add_labels(bars, values, format_str='{:.1f}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
add_labels(bars1, mpg)
add_labels(bars2, hp)
add_labels(bars3, weight * 100) # 원래 중량값으로 표시
# 차량 수 레이블
for i, count in enumerate(counts):
ax2.text(i, count, f'{count}대', ha='center', va='bottom')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(manufacturer_analysis))
width = 0.2
# numpy 배열로 변환
mpg = manufacturer_analysis['평균_연비'].to_numpy()
hp = manufacturer_analysis['평균_마력'].to_numpy()
weight = manufacturer_analysis['평균_중량'].to_numpy()/100 # 중량은 스케일 조정
counts = manufacturer_analysis['차량_수'].to_numpy()
# 막대 그래프 생성
fig, ax1 = plt.subplots(figsize=(12, 6))
ax2 = ax1.twinx()
# 막대 그래프: 평균 연비, 마력, 중량(스케일 조정)
bars1 = ax1.bar(x - width, mpg, width, label='평균 연비(mpg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, weight, width, label='평균 중량(×100kg)', color='salmon')
# 선 그래프: 차량 수
line = ax2.plot(x, counts, 'ko-', linewidth=2, label='차량 수', markersize=8)
# 그래프 꾸미기
plt.title('제조국가별 자동차 특성 분석', pad=20, size=15)
ax1.set_xlabel('제조국')
ax1.set_ylabel('연비/마력/중량')
ax2.set_ylabel('차량 수')
# x축 레이블 설정
plt.xticks(x, manufacturer_analysis['origin'])
# 데이터 레이블 추가
def add_labels(bars, values, format_str='{:.1f}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
add_labels(bars1, mpg)
add_labels(bars2, hp)
add_labels(bars3, weight * 100) # 원래 중량값으로 표시
# 차량 수 레이블
for i, count in enumerate(counts):
ax2.text(i, count, f'{count}대', ha='center', va='bottom')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.tight_layout()
plt.show()
5. 연도별 트렌드 분석
year_analysis = (
mpg_df.group_by('model_year')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('weight').mean().alias('평균_중량'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('displacement').mean().alias('평균_배기량'),
pl.count().alias('차량_수')
])
.sort('model_year')
)
print("연도별 트렌드 분석:")
print(year_analysis)
year_analysis = (
mpg_df.group_by('model_year')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('weight').mean().alias('평균_중량'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('displacement').mean().alias('평균_배기량'),
pl.count().alias('차량_수')
])
.sort('model_year')
)
print("연도별 트렌드 분석:")
print(year_analysis)
연도별 트렌드 분석:
shape: (13, 6)
┌────────────┬───────────┬─────────────┬────────────┬─────────────┬─────────┐
│ model_year ┆ 평균_연비 ┆ 평균_중량 ┆ 평균_마력 ┆ 평균_배기량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════════╪═══════════╪═════════════╪════════════╪═════════════╪═════════╡
│ 70 ┆ 17.689655 ┆ 3372.793103 ┆ 147.827586 ┆ 281.413793 ┆ 29 │
│ 71 ┆ 21.25 ┆ 2995.428571 ┆ 107.037037 ┆ 209.75 ┆ 28 │
│ 72 ┆ 18.714286 ┆ 3237.714286 ┆ 120.178571 ┆ 218.375 ┆ 28 │
│ 73 ┆ 17.1 ┆ 3419.025 ┆ 130.475 ┆ 256.875 ┆ 40 │
│ 74 ┆ 22.703704 ┆ 2877.925926 ┆ 94.230769 ┆ 171.740741 ┆ 27 │
│ … ┆ … ┆ … ┆ … ┆ … ┆ … │
│ 78 ┆ 24.061111 ┆ 2861.805556 ┆ 99.694444 ┆ 177.805556 ┆ 36 │
│ 79 ┆ 25.093103 ┆ 3055.344828 ┆ 101.206897 ┆ 206.689655 ┆ 29 │
│ 80 ┆ 33.696552 ┆ 2436.655172 ┆ 77.481481 ┆ 115.827586 ┆ 29 │
│ 81 ┆ 30.334483 ┆ 2522.931034 ┆ 81.035714 ┆ 135.310345 ┆ 29 │
│ 82 ┆ 31.709677 ┆ 2453.548387 ┆ 81.466667 ┆ 128.870968 ┆ 31 │
└────────────┴───────────┴─────────────┴────────────┴─────────────┴─────────┘
연도별 트렌드 분석:
shape: (13, 6)
┌────────────┬───────────┬─────────────┬────────────┬─────────────┬─────────┐
│ model_year ┆ 평균_연비 ┆ 평균_중량 ┆ 평균_마력 ┆ 평균_배기량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════════╪═══════════╪═════════════╪════════════╪═════════════╪═════════╡
│ 70 ┆ 17.689655 ┆ 3372.793103 ┆ 147.827586 ┆ 281.413793 ┆ 29 │
│ 71 ┆ 21.25 ┆ 2995.428571 ┆ 107.037037 ┆ 209.75 ┆ 28 │
│ 72 ┆ 18.714286 ┆ 3237.714286 ┆ 120.178571 ┆ 218.375 ┆ 28 │
│ 73 ┆ 17.1 ┆ 3419.025 ┆ 130.475 ┆ 256.875 ┆ 40 │
│ 74 ┆ 22.703704 ┆ 2877.925926 ┆ 94.230769 ┆ 171.740741 ┆ 27 │
│ … ┆ … ┆ … ┆ … ┆ … ┆ … │
│ 78 ┆ 24.061111 ┆ 2861.805556 ┆ 99.694444 ┆ 177.805556 ┆ 36 │
│ 79 ┆ 25.093103 ┆ 3055.344828 ┆ 101.206897 ┆ 206.689655 ┆ 29 │
│ 80 ┆ 33.696552 ┆ 2436.655172 ┆ 77.481481 ┆ 115.827586 ┆ 29 │
│ 81 ┆ 30.334483 ┆ 2522.931034 ┆ 81.035714 ┆ 135.310345 ┆ 29 │
│ 82 ┆ 31.709677 ┆ 2453.548387 ┆ 81.466667 ┆ 128.870968 ┆ 31 │
└────────────┴───────────┴─────────────┴────────────┴─────────────┴─────────┘
# 그래프 크기 설정
plt.figure(figsize=(15, 10))
# 두 개의 서브플롯 생성
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 10))
# 첫 번째 서브플롯: 연비와 차량 수
ax1_twin = ax1.twinx()
# 데이터 준비
years = year_analysis['model_year'].to_numpy()
mpg = year_analysis['평균_연비'].to_numpy()
counts = year_analysis['차량_수'].to_numpy()
# 선 그래프: 평균 연비
line1 = ax1.plot(years, mpg, 'bo-', linewidth=2, label='평균 연비(mpg)', markersize=8)
# 막대 그래프: 차량 수
bars = ax1_twin.bar(years, counts, alpha=0.3, color='gray', label='차량 수')
# 데이터 레이블 추가
for i, (m, c) in enumerate(zip(mpg, counts)):
ax1.text(years[i], m, f'{m:.1f}', ha='center', va='bottom')
ax1_twin.text(years[i], c, f'{c}대', ha='center', va='bottom')
ax1.set_title('연도별 평균 연비와 차량 수', pad=20, size=13)
ax1.set_xlabel('연도')
ax1.set_ylabel('평균 연비(mpg)')
ax1_twin.set_ylabel('차량 수')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax1_twin.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
# 두 번째 서브플롯: 마력, 중량, 배기량
# 왼쪽 축은 마력용, 오른쪽 축은 중량과 배기량용
ax2_twin = ax2.twinx()
# 데이터 준비 (스케일 조정)
hp = year_analysis['평균_마력'].to_numpy()
weight = year_analysis['평균_중량'].to_numpy() / 100 # 스케일 조정 변경
displacement = year_analysis['평균_배기량'].to_numpy() / 10 # 스케일 조정 변경
# 선 그래프
line2 = ax2.plot(years, hp, 'ro-', linewidth=2, label='평균 마력', markersize=8)
line3 = ax2_twin.plot(years, weight, 'go-', linewidth=2, label='평균 중량(×100kg)', markersize=8)
line4 = ax2_twin.plot(years, displacement, 'mo-', linewidth=2, label='평균 배기량(×10cc)', markersize=8)
# 데이터 레이블 추가
for i, (h, w, d) in enumerate(zip(hp, weight, displacement)):
ax2.text(years[i], h, f'{h:.1f}', ha='right', va='bottom')
ax2_twin.text(years[i], w, f'{w*100:.0f}kg', ha='right', va='bottom')
ax2_twin.text(years[i], d, f'{d*10:.0f}cc', ha='left', va='bottom')
ax2.set_title('연도별 성능 지표 변화', pad=20, size=13)
ax2.set_xlabel('연도')
ax2.set_ylabel('마력')
ax2_twin.set_ylabel('중량/배기량')
# 범례 통합
lines3, labels3 = ax2.get_legend_handles_labels()
lines4, labels4 = ax2_twin.get_legend_handles_labels()
ax2.legend(lines3 + lines4, labels3 + labels4, loc='upper right')
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(15, 10))
# 두 개의 서브플롯 생성
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 10))
# 첫 번째 서브플롯: 연비와 차량 수
ax1_twin = ax1.twinx()
# 데이터 준비
years = year_analysis['model_year'].to_numpy()
mpg = year_analysis['평균_연비'].to_numpy()
counts = year_analysis['차량_수'].to_numpy()
# 선 그래프: 평균 연비
line1 = ax1.plot(years, mpg, 'bo-', linewidth=2, label='평균 연비(mpg)', markersize=8)
# 막대 그래프: 차량 수
bars = ax1_twin.bar(years, counts, alpha=0.3, color='gray', label='차량 수')
# 데이터 레이블 추가
for i, (m, c) in enumerate(zip(mpg, counts)):
ax1.text(years[i], m, f'{m:.1f}', ha='center', va='bottom')
ax1_twin.text(years[i], c, f'{c}대', ha='center', va='bottom')
ax1.set_title('연도별 평균 연비와 차량 수', pad=20, size=13)
ax1.set_xlabel('연도')
ax1.set_ylabel('평균 연비(mpg)')
ax1_twin.set_ylabel('차량 수')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax1_twin.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
# 두 번째 서브플롯: 마력, 중량, 배기량
# 왼쪽 축은 마력용, 오른쪽 축은 중량과 배기량용
ax2_twin = ax2.twinx()
# 데이터 준비 (스케일 조정)
hp = year_analysis['평균_마력'].to_numpy()
weight = year_analysis['평균_중량'].to_numpy() / 100 # 스케일 조정 변경
displacement = year_analysis['평균_배기량'].to_numpy() / 10 # 스케일 조정 변경
# 선 그래프
line2 = ax2.plot(years, hp, 'ro-', linewidth=2, label='평균 마력', markersize=8)
line3 = ax2_twin.plot(years, weight, 'go-', linewidth=2, label='평균 중량(×100kg)', markersize=8)
line4 = ax2_twin.plot(years, displacement, 'mo-', linewidth=2, label='평균 배기량(×10cc)', markersize=8)
# 데이터 레이블 추가
for i, (h, w, d) in enumerate(zip(hp, weight, displacement)):
ax2.text(years[i], h, f'{h:.1f}', ha='right', va='bottom')
ax2_twin.text(years[i], w, f'{w*100:.0f}kg', ha='right', va='bottom')
ax2_twin.text(years[i], d, f'{d*10:.0f}cc', ha='left', va='bottom')
ax2.set_title('연도별 성능 지표 변화', pad=20, size=13)
ax2.set_xlabel('연도')
ax2.set_ylabel('마력')
ax2_twin.set_ylabel('중량/배기량')
# 범례 통합
lines3, labels3 = ax2.get_legend_handles_labels()
lines4, labels4 = ax2_twin.get_legend_handles_labels()
ax2.legend(lines3 + lines4, labels3 + labels4, loc='upper right')
plt.tight_layout()
plt.show()
6. 실린더 수별 분석
cylinder_analysis = (
mpg_df.group_by('cylinders')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('displacement').mean().alias('평균_배기량'),
pl.count().alias('차량_수')
])
.sort('cylinders')
)
print("실린더 수별 분석:")
print(cylinder_analysis)
cylinder_analysis = (
mpg_df.group_by('cylinders')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('displacement').mean().alias('평균_배기량'),
pl.count().alias('차량_수')
])
.sort('cylinders')
)
print("실린더 수별 분석:")
print(cylinder_analysis)
실린더 수별 분석:
shape: (5, 5)
┌───────────┬───────────┬────────────┬─────────────┬─────────┐
│ cylinders ┆ 평균_연비 ┆ 평균_마력 ┆ 평균_배기량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞═══════════╪═══════════╪════════════╪═════════════╪═════════╡
│ 3 ┆ 20.55 ┆ 99.25 ┆ 72.5 ┆ 4 │
│ 4 ┆ 29.286765 ┆ 78.281407 ┆ 109.796569 ┆ 204 │
│ 5 ┆ 27.366667 ┆ 82.333333 ┆ 145.0 ┆ 3 │
│ 6 ┆ 19.985714 ┆ 101.506024 ┆ 218.142857 ┆ 84 │
│ 8 ┆ 14.963107 ┆ 158.300971 ┆ 345.009709 ┆ 103 │
└───────────┴───────────┴────────────┴─────────────┴─────────┘
실린더 수별 분석:
shape: (5, 5)
┌───────────┬───────────┬────────────┬─────────────┬─────────┐
│ cylinders ┆ 평균_연비 ┆ 평균_마력 ┆ 평균_배기량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞═══════════╪═══════════╪════════════╪═════════════╪═════════╡
│ 3 ┆ 20.55 ┆ 99.25 ┆ 72.5 ┆ 4 │
│ 4 ┆ 29.286765 ┆ 78.281407 ┆ 109.796569 ┆ 204 │
│ 5 ┆ 27.366667 ┆ 82.333333 ┆ 145.0 ┆ 3 │
│ 6 ┆ 19.985714 ┆ 101.506024 ┆ 218.142857 ┆ 84 │
│ 8 ┆ 14.963107 ┆ 158.300971 ┆ 345.009709 ┆ 103 │
└───────────┴───────────┴────────────┴─────────────┴─────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(cylinder_analysis))
width = 0.2
# numpy 배열로 변환
mpg = cylinder_analysis['평균_연비'].to_numpy()
hp = cylinder_analysis['평균_마력'].to_numpy()
disp = cylinder_analysis['평균_배기량'].to_numpy()/10 # 배기량 스케일 조정
counts = cylinder_analysis['차량_수'].to_numpy()
# 주 축과 보조축 설정
ax1 = plt.gca()
ax2 = ax1.twinx()
# 막대 그래프: 평균 연비, 마력, 배기량
bars1 = ax1.bar(x - width, mpg, width, label='평균 연비(mpg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, disp, width, label='평균 배기량(×10cc)', color='salmon')
# 선 그래프: 차량 수
line = ax2.plot(x, counts, 'ko-', linewidth=2, label='차량 수', markersize=8)
# 그래프 꾸미기
plt.title('실린더 수별 성능 분석', pad=20, size=15)
ax1.set_xlabel('실린더 수')
ax1.set_ylabel('연비/마력/배기량')
ax2.set_ylabel('차량 수')
# x축 레이블 설정
plt.xticks(x, cylinder_analysis['cylinders'])
# 데이터 레이블 추가
def add_value_labels(bars, values, format_str='{}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
# 각 막대에 값 추가
add_value_labels(bars1, mpg, '{:.1f}')
add_value_labels(bars2, hp, '{:.1f}')
add_value_labels(bars3, disp*10, '{:.0f}') # 원래 배기량 값으로 표시
# 차량 수 레이블
for i, count in enumerate(counts):
ax2.text(i, count, f'{count}대', ha='center', va='bottom')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(cylinder_analysis))
width = 0.2
# numpy 배열로 변환
mpg = cylinder_analysis['평균_연비'].to_numpy()
hp = cylinder_analysis['평균_마력'].to_numpy()
disp = cylinder_analysis['평균_배기량'].to_numpy()/10 # 배기량 스케일 조정
counts = cylinder_analysis['차량_수'].to_numpy()
# 주 축과 보조축 설정
ax1 = plt.gca()
ax2 = ax1.twinx()
# 막대 그래프: 평균 연비, 마력, 배기량
bars1 = ax1.bar(x - width, mpg, width, label='평균 연비(mpg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, disp, width, label='평균 배기량(×10cc)', color='salmon')
# 선 그래프: 차량 수
line = ax2.plot(x, counts, 'ko-', linewidth=2, label='차량 수', markersize=8)
# 그래프 꾸미기
plt.title('실린더 수별 성능 분석', pad=20, size=15)
ax1.set_xlabel('실린더 수')
ax1.set_ylabel('연비/마력/배기량')
ax2.set_ylabel('차량 수')
# x축 레이블 설정
plt.xticks(x, cylinder_analysis['cylinders'])
# 데이터 레이블 추가
def add_value_labels(bars, values, format_str='{}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
# 각 막대에 값 추가
add_value_labels(bars1, mpg, '{:.1f}')
add_value_labels(bars2, hp, '{:.1f}')
add_value_labels(bars3, disp*10, '{:.0f}') # 원래 배기량 값으로 표시
# 차량 수 레이블
for i, count in enumerate(counts):
ax2.text(i, count, f'{count}대', ha='center', va='bottom')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.tight_layout()
plt.show()
7. 출력 국가별 분석
origin_analysis = (
mpg_df.group_by('origin')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('weight').mean().alias('평균_중량'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('acceleration').mean().alias('평균_가속'),
pl.count().alias('차량_수')
])
)
print("출력 국가별 분석:")
print(origin_analysis)
origin_analysis = (
mpg_df.group_by('origin')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('weight').mean().alias('평균_중량'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('acceleration').mean().alias('평균_가속'),
pl.count().alias('차량_수')
])
)
print("출력 국가별 분석:")
print(origin_analysis)
출력 국가별 분석:
shape: (3, 6)
┌────────┬───────────┬─────────────┬───────────┬───────────┬─────────┐
│ origin ┆ 평균_연비 ┆ 평균_중량 ┆ 평균_마력 ┆ 평균_가속 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════╪═══════════╪═════════════╪═══════════╪═══════════╪═════════╡
│ japan ┆ 30.450633 ┆ 2221.227848 ┆ 79.835443 ┆ 16.172152 ┆ 79 │
│ usa ┆ 20.083534 ┆ 3361.931727 ┆ 119.04898 ┆ 15.033735 ┆ 249 │
│ europe ┆ 27.891429 ┆ 2423.3 ┆ 80.558824 ┆ 16.787143 ┆ 70 │
└────────┴───────────┴─────────────┴───────────┴───────────┴─────────┘
출력 국가별 분석:
shape: (3, 6)
┌────────┬───────────┬─────────────┬───────────┬───────────┬─────────┐
│ origin ┆ 평균_연비 ┆ 평균_중량 ┆ 평균_마력 ┆ 평균_가속 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════╪═══════════╪═════════════╪═══════════╪═══════════╪═════════╡
│ japan ┆ 30.450633 ┆ 2221.227848 ┆ 79.835443 ┆ 16.172152 ┆ 79 │
│ usa ┆ 20.083534 ┆ 3361.931727 ┆ 119.04898 ┆ 15.033735 ┆ 249 │
│ europe ┆ 27.891429 ┆ 2423.3 ┆ 80.558824 ┆ 16.787143 ┆ 70 │
└────────┴───────────┴─────────────┴───────────┴───────────┴─────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 8))
# 두 개의 서브플롯 생성
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
# 첫 번째 서브플롯: 연비, 마력, 가속
x = np.arange(len(origin_analysis))
width = 0.25
# 데이터 준비 및 정규화 (값들의 스케일을 맞추기 위해)
mpg = origin_analysis['평균_연비'].to_numpy()
hp = origin_analysis['평균_마력'].to_numpy()
acc = origin_analysis['평균_가속'].to_numpy() * 2 # 가속 값을 두 배로 키움
# 막대 그래프
bars1 = ax1.bar(x - width, mpg, width, label='평균 연비(mpg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, acc, width, label='평균 가속(×2s)', color='salmon')
# 데이터 레이블 추가
for bars, values, format_str in zip([bars1, bars2, bars3],
[mpg, hp, acc/2], # 가속 값은 원래대로 표시
['{:.1f}', '{:.1f}', '{:.1f}s']):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
ax1.set_title('국가별 성능 지표 비교', pad=20)
ax1.set_xticks(x)
ax1.set_xticklabels(origin_analysis['origin'])
ax1.legend()
# 두 번째 서브플롯: 중량과 차량 수
ax2_twin = ax2.twinx()
# 데이터 준비
weight = origin_analysis['평균_중량'].to_numpy()/100 # 스케일 조정
counts = origin_analysis['차량_수'].to_numpy()
# 막대 그래프: 평균 중량
bars4 = ax2.bar(x - width/2, weight, width, label='평균 중량(×100kg)', color='purple', alpha=0.6)
# 막대 그래프: 차량 수
bars5 = ax2.bar(x + width/2, counts, width, label='차량 수', color='gray', alpha=0.6)
# 데이터 레이블 추가
for bar, value in zip(bars4, weight*100): # 원래 중량값으로 표시
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height,
f'{value:.0f}kg',
ha='center', va='bottom')
for bar, value in zip(bars5, counts):
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height,
f'{value}대',
ha='center', va='bottom')
ax2.set_title('국가별 중량과 차량 수', pad=20)
ax2.set_xticks(x)
ax2.set_xticklabels(origin_analysis['origin'])
ax2.legend(loc='upper left')
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 8))
# 두 개의 서브플롯 생성
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
# 첫 번째 서브플롯: 연비, 마력, 가속
x = np.arange(len(origin_analysis))
width = 0.25
# 데이터 준비 및 정규화 (값들의 스케일을 맞추기 위해)
mpg = origin_analysis['평균_연비'].to_numpy()
hp = origin_analysis['평균_마력'].to_numpy()
acc = origin_analysis['평균_가속'].to_numpy() * 2 # 가속 값을 두 배로 키움
# 막대 그래프
bars1 = ax1.bar(x - width, mpg, width, label='평균 연비(mpg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, acc, width, label='평균 가속(×2s)', color='salmon')
# 데이터 레이블 추가
for bars, values, format_str in zip([bars1, bars2, bars3],
[mpg, hp, acc/2], # 가속 값은 원래대로 표시
['{:.1f}', '{:.1f}', '{:.1f}s']):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
ax1.set_title('국가별 성능 지표 비교', pad=20)
ax1.set_xticks(x)
ax1.set_xticklabels(origin_analysis['origin'])
ax1.legend()
# 두 번째 서브플롯: 중량과 차량 수
ax2_twin = ax2.twinx()
# 데이터 준비
weight = origin_analysis['평균_중량'].to_numpy()/100 # 스케일 조정
counts = origin_analysis['차량_수'].to_numpy()
# 막대 그래프: 평균 중량
bars4 = ax2.bar(x - width/2, weight, width, label='평균 중량(×100kg)', color='purple', alpha=0.6)
# 막대 그래프: 차량 수
bars5 = ax2.bar(x + width/2, counts, width, label='차량 수', color='gray', alpha=0.6)
# 데이터 레이블 추가
for bar, value in zip(bars4, weight*100): # 원래 중량값으로 표시
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height,
f'{value:.0f}kg',
ha='center', va='bottom')
for bar, value in zip(bars5, counts):
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height,
f'{value}대',
ha='center', va='bottom')
ax2.set_title('국가별 중량과 차량 수', pad=20)
ax2.set_xticks(x)
ax2.set_xticklabels(origin_analysis['origin'])
ax2.legend(loc='upper left')
plt.tight_layout()
plt.show()
8. 연비 구간별 분석
mpg_ranges = (
mpg_df.with_columns([
pl.col('mpg')
.cut(breaks=[0, 15, 20, 25, 30, 35, 50],
labels=['0', '1~15', '15-20', '20-25', '25-30', '30-35', '35-50', '50+'])
.alias('mpg_range')
])
.group_by('mpg_range')
.agg([
pl.col('weight').mean().alias('평균_중량'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('acceleration').mean().alias('평균_가속'),
pl.count().alias('차량_수')
])
.sort('mpg_range')
)
print("연비 구간별 분석:")
print(mpg_ranges)
mpg_ranges = (
mpg_df.with_columns([
pl.col('mpg')
.cut(breaks=[0, 15, 20, 25, 30, 35, 50],
labels=['0', '1~15', '15-20', '20-25', '25-30', '30-35', '35-50', '50+'])
.alias('mpg_range')
])
.group_by('mpg_range')
.agg([
pl.col('weight').mean().alias('평균_중량'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('acceleration').mean().alias('평균_가속'),
pl.count().alias('차량_수')
])
.sort('mpg_range')
)
print("연비 구간별 분석:")
print(mpg_ranges)
연비 구간별 분석:
shape: (6, 5)
┌───────────┬─────────────┬────────────┬───────────┬─────────┐
│ mpg_range ┆ 평균_중량 ┆ 평균_마력 ┆ 평균_가속 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ cat ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞═══════════╪═════════════╪════════════╪═══════════╪═════════╡
│ 1~15 ┆ 4196.608696 ┆ 162.652174 ┆ 12.926087 ┆ 69 │
│ 15-20 ┆ 3463.725275 ┆ 118.340659 ┆ 15.26044 ┆ 91 │
│ 20-25 ┆ 2749.5125 ┆ 94.210526 ┆ 16.26375 ┆ 80 │
│ 25-30 ┆ 2401.465753 ┆ 81.465753 ┆ 16.386301 ┆ 73 │
│ 30-35 ┆ 2182.764706 ┆ 72.94 ┆ 16.368627 ┆ 51 │
│ 35-50 ┆ 2084.558824 ┆ 66.848485 ┆ 17.158824 ┆ 34 │
└───────────┴─────────────┴────────────┴───────────┴─────────┘
연비 구간별 분석:
shape: (6, 5)
┌───────────┬─────────────┬────────────┬───────────┬─────────┐
│ mpg_range ┆ 평균_중량 ┆ 평균_마력 ┆ 평균_가속 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ cat ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞═══════════╪═════════════╪════════════╪═══════════╪═════════╡
│ 1~15 ┆ 4196.608696 ┆ 162.652174 ┆ 12.926087 ┆ 69 │
│ 15-20 ┆ 3463.725275 ┆ 118.340659 ┆ 15.26044 ┆ 91 │
│ 20-25 ┆ 2749.5125 ┆ 94.210526 ┆ 16.26375 ┆ 80 │
│ 25-30 ┆ 2401.465753 ┆ 81.465753 ┆ 16.386301 ┆ 73 │
│ 30-35 ┆ 2182.764706 ┆ 72.94 ┆ 16.368627 ┆ 51 │
│ 35-50 ┆ 2084.558824 ┆ 66.848485 ┆ 17.158824 ┆ 34 │
└───────────┴─────────────┴────────────┴───────────┴─────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(mpg_ranges))
width = 0.2
# numpy 배열로 변환 및 스케일 조정
weight = mpg_ranges['평균_중량'].to_numpy()/100 # 중량 스케일 조정
hp = mpg_ranges['평균_마력'].to_numpy()
acc = mpg_ranges['평균_가속'].to_numpy()
counts = mpg_ranges['차량_수'].to_numpy()
# 주 축과 보조축 설정
ax1 = plt.gca()
ax2 = ax1.twinx()
# 막대 그래프: 중량, 마력, 가속
bars1 = ax1.bar(x - width, weight, width, label='평균 중량(×100kg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, acc, width, label='평균 가속(s)', color='salmon')
# 선 그래프: 차량 수
line = ax2.plot(x, counts, 'ko-', linewidth=2, label='차량 수', markersize=8)
# 그래프 꾸미기
plt.title('연비 구간별 차량 특성 분석', pad=20, size=15)
ax1.set_xlabel('연비 구간 (mpg)')
ax1.set_ylabel('중량/마력/가속')
ax2.set_ylabel('차량 수')
# x축 레이블 설정
plt.xticks(x, mpg_ranges['mpg_range'], rotation=45)
# 데이터 레이블 추가
def add_value_labels(bars, values, format_str='{}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom', rotation=90)
# 각 막대에 값 추가
add_value_labels(bars1, weight*100, '{:.0f}kg') # 원래 중량값으로 표시
add_value_labels(bars2, hp, '{:.1f}')
add_value_labels(bars3, acc, '{:.1f}s')
# 차량 수 레이블
for i, count in enumerate(counts):
ax2.text(i, count, f'{count}대', ha='center', va='bottom')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(mpg_ranges))
width = 0.2
# numpy 배열로 변환 및 스케일 조정
weight = mpg_ranges['평균_중량'].to_numpy()/100 # 중량 스케일 조정
hp = mpg_ranges['평균_마력'].to_numpy()
acc = mpg_ranges['평균_가속'].to_numpy()
counts = mpg_ranges['차량_수'].to_numpy()
# 주 축과 보조축 설정
ax1 = plt.gca()
ax2 = ax1.twinx()
# 막대 그래프: 중량, 마력, 가속
bars1 = ax1.bar(x - width, weight, width, label='평균 중량(×100kg)', color='lightblue')
bars2 = ax1.bar(x, hp, width, label='평균 마력', color='lightgreen')
bars3 = ax1.bar(x + width, acc, width, label='평균 가속(s)', color='salmon')
# 선 그래프: 차량 수
line = ax2.plot(x, counts, 'ko-', linewidth=2, label='차량 수', markersize=8)
# 그래프 꾸미기
plt.title('연비 구간별 차량 특성 분석', pad=20, size=15)
ax1.set_xlabel('연비 구간 (mpg)')
ax1.set_ylabel('중량/마력/가속')
ax2.set_ylabel('차량 수')
# x축 레이블 설정
plt.xticks(x, mpg_ranges['mpg_range'], rotation=45)
# 데이터 레이블 추가
def add_value_labels(bars, values, format_str='{}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom', rotation=90)
# 각 막대에 값 추가
add_value_labels(bars1, weight*100, '{:.0f}kg') # 원래 중량값으로 표시
add_value_labels(bars2, hp, '{:.1f}')
add_value_labels(bars3, acc, '{:.1f}s')
# 차량 수 레이블
for i, count in enumerate(counts):
ax2.text(i, count, f'{count}대', ha='center', va='bottom')
# 범례 통합
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
plt.tight_layout()
plt.show()
9. 상관관계 분석
correlations = mpg_df.select([
pl.corr('mpg', 'weight').alias('연비_중량_상관계수'),
pl.corr('mpg', 'horsepower').alias('연비_마력_상관계수'),
pl.corr('mpg', 'displacement').alias('연비_배기량_상관계수'),
pl.corr('horsepower', 'weight').alias('마력_중량_상관계수')
])
print("특성간 상관관계:")
print(correlations)
correlations = mpg_df.select([
pl.corr('mpg', 'weight').alias('연비_중량_상관계수'),
pl.corr('mpg', 'horsepower').alias('연비_마력_상관계수'),
pl.corr('mpg', 'displacement').alias('연비_배기량_상관계수'),
pl.corr('horsepower', 'weight').alias('마력_중량_상관계수')
])
print("특성간 상관관계:")
print(correlations)
특성간 상관관계:
shape: (1, 4)
┌────────────────────┬────────────────────┬──────────────────────┬────────────────────┐
│ 연비_중량_상관계수 ┆ 연비_마력_상관계수 ┆ 연비_배기량_상관계수 ┆ 마력_중량_상관계수 │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════════════════╪════════════════════╪══════════════════════╪════════════════════╡
│ -0.831741 ┆ -0.778427 ┆ -0.804203 ┆ 0.864538 │
└────────────────────┴────────────────────┴──────────────────────┴────────────────────┘
특성간 상관관계:
shape: (1, 4)
┌────────────────────┬────────────────────┬──────────────────────┬────────────────────┐
│ 연비_중량_상관계수 ┆ 연비_마력_상관계수 ┆ 연비_배기량_상관계수 ┆ 마력_중량_상관계수 │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════════════════╪════════════════════╪══════════════════════╪════════════════════╡
│ -0.831741 ┆ -0.778427 ┆ -0.804203 ┆ 0.864538 │
└────────────────────┴────────────────────┴──────────────────────┴────────────────────┘
# 그래프 크기 설정
plt.figure(figsize=(10, 8))
# 상관계수 행렬 생성
features = ['연비', '중량', '마력', '배기량']
corr_matrix = np.array([
[1.0, correlations['연비_중량_상관계수'][0],
correlations['연비_마력_상관계수'][0],
correlations['연비_배기량_상관계수'][0]],
[correlations['연비_중량_상관계수'][0], 1.0,
correlations['마력_중량_상관계수'][0], 0.9],
[correlations['연비_마력_상관계수'][0],
correlations['마력_중량_상관계수'][0], 1.0, 0.9],
[correlations['연비_배기량_상관계수'][0], 0.9, 0.9, 1.0]
])
# 히트맵 생성
sns.heatmap(corr_matrix,
annot=True, # 값 표시
fmt='.3f', # 소수점 3자리
cmap='RdYlBu_r', # 색상 맵
xticklabels=features,
yticklabels=features,
center=0, # 중앙값 (색상 기준)
vmin=-1, vmax=1, # 값의 범위
square=True) # 정사각형 셀
plt.title('자동차 특성간 상관관계 히트맵', pad=20)
# 레이아웃 조정
plt.tight_layout()
plt.show()
# 추가로 산점도 행렬도 그려보기
plt.figure(figsize=(12, 12))
scatter_vars = ['mpg', 'weight', 'horsepower', 'displacement']
scatter_labels = ['연비', '중량', '마력', '배기량']
pd_df = mpg_df.select(scatter_vars).to_pandas()
pd_df.columns = scatter_labels
sns.pairplot(pd_df, diag_kind='kde')
plt.suptitle('자동차 특성간 산점도 행렬', y=1.02, size=15)
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(10, 8))
# 상관계수 행렬 생성
features = ['연비', '중량', '마력', '배기량']
corr_matrix = np.array([
[1.0, correlations['연비_중량_상관계수'][0],
correlations['연비_마력_상관계수'][0],
correlations['연비_배기량_상관계수'][0]],
[correlations['연비_중량_상관계수'][0], 1.0,
correlations['마력_중량_상관계수'][0], 0.9],
[correlations['연비_마력_상관계수'][0],
correlations['마력_중량_상관계수'][0], 1.0, 0.9],
[correlations['연비_배기량_상관계수'][0], 0.9, 0.9, 1.0]
])
# 히트맵 생성
sns.heatmap(corr_matrix,
annot=True, # 값 표시
fmt='.3f', # 소수점 3자리
cmap='RdYlBu_r', # 색상 맵
xticklabels=features,
yticklabels=features,
center=0, # 중앙값 (색상 기준)
vmin=-1, vmax=1, # 값의 범위
square=True) # 정사각형 셀
plt.title('자동차 특성간 상관관계 히트맵', pad=20)
# 레이아웃 조정
plt.tight_layout()
plt.show()
# 추가로 산점도 행렬도 그려보기
plt.figure(figsize=(12, 12))
scatter_vars = ['mpg', 'weight', 'horsepower', 'displacement']
scatter_labels = ['연비', '중량', '마력', '배기량']
pd_df = mpg_df.select(scatter_vars).to_pandas()
pd_df.columns = scatter_labels
sns.pairplot(pd_df, diag_kind='kde')
plt.suptitle('자동차 특성간 산점도 행렬', y=1.02, size=15)
plt.show()
10. 연도별 연비 개선도 분석
efficiency_improvement = (
mpg_df.group_by(['origin', 'model_year'])
.agg([
pl.col('mpg').mean().alias('평균_연비')
])
.sort(['origin', 'model_year'])
.group_by('origin')
.agg([
(pl.col('평균_연비').max() - pl.col('평균_연비').min()).alias('연비_개선폭'),
pl.col('평균_연비').mean().alias('전체_평균_연비')
])
.sort('연비_개선폭', descending=True)
)
print("제조사별 연비 개선도:")
print(efficiency_improvement)
efficiency_improvement = (
mpg_df.group_by(['origin', 'model_year'])
.agg([
pl.col('mpg').mean().alias('평균_연비')
])
.sort(['origin', 'model_year'])
.group_by('origin')
.agg([
(pl.col('평균_연비').max() - pl.col('평균_연비').min()).alias('연비_개선폭'),
pl.col('평균_연비').mean().alias('전체_평균_연비')
])
.sort('연비_개선폭', descending=True)
)
print("제조사별 연비 개선도:")
print(efficiency_improvement)
제조사별 연비 개선도:
shape: (3, 3)
┌────────┬─────────────┬────────────────┐
│ origin ┆ 연비_개선폭 ┆ 전체_평균_연비 │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪═════════════╪════════════════╡
│ europe ┆ 18.0 ┆ 28.401068 │
│ japan ┆ 15.4 ┆ 29.025748 │
│ usa ┆ 14.415517 ┆ 20.682185 │
└────────┴─────────────┴────────────────┘
제조사별 연비 개선도:
shape: (3, 3)
┌────────┬─────────────┬────────────────┐
│ origin ┆ 연비_개선폭 ┆ 전체_평균_연비 │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪═════════════╪════════════════╡
│ europe ┆ 18.0 ┆ 28.401068 │
│ japan ┆ 15.4 ┆ 29.025748 │
│ usa ┆ 14.415517 ┆ 20.682185 │
└────────┴─────────────┴────────────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(efficiency_improvement))
width = 0.35
# numpy 배열로 변환
improvement = efficiency_improvement['연비_개선폭'].to_numpy()
avg_mpg = efficiency_improvement['전체_평균_연비'].to_numpy()
# 주 축 설정
ax1 = plt.gca()
ax2 = ax1.twinx()
# 막대 그래프: 연비 개선폭
bars1 = ax1.bar(x - width/2, improvement, width,
label='연비 개선폭', color='lightblue')
# 막대 그래프: 전체 평균 연비
bars2 = ax1.bar(x + width/2, avg_mpg, width,
label='전체 평균 연비', color='lightgreen')
# 데이터 레이블 추가
def add_labels(bars, values, format_str='{:.1f}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
add_labels(bars1, improvement)
add_labels(bars2, avg_mpg)
# 그래프 꾸미기
plt.title('제조국가별 연비 개선도 분석', pad=20, size=15)
ax1.set_xlabel('제조국')
ax1.set_ylabel('연비 (mpg)')
# x축 레이블 설정
plt.xticks(x, efficiency_improvement['origin'])
# 범례
ax1.legend(loc='upper right')
# 그리드 추가
ax1.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# 시간에 따른 변화를 보여주는 라인 플롯 추가
yearly_data = (
mpg_df.group_by(['origin', 'model_year'])
.agg([
pl.col('mpg').mean().alias('평균_연비')
])
.sort(['origin', 'model_year'])
)
plt.figure(figsize=(12, 6))
# 각 제조국별로 라인 플롯 그리기
for country in yearly_data['origin'].unique():
country_data = yearly_data.filter(pl.col('origin') == country)
plt.plot(country_data['model_year'],
country_data['평균_연비'],
'o-', linewidth=2, label=country, markersize=8)
plt.title('제조국가별 연도별 평균 연비 변화', pad=20, size=15)
plt.xlabel('연도')
plt.ylabel('평균 연비 (mpg)')
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
# 데이터 준비
x = np.arange(len(efficiency_improvement))
width = 0.35
# numpy 배열로 변환
improvement = efficiency_improvement['연비_개선폭'].to_numpy()
avg_mpg = efficiency_improvement['전체_평균_연비'].to_numpy()
# 주 축 설정
ax1 = plt.gca()
ax2 = ax1.twinx()
# 막대 그래프: 연비 개선폭
bars1 = ax1.bar(x - width/2, improvement, width,
label='연비 개선폭', color='lightblue')
# 막대 그래프: 전체 평균 연비
bars2 = ax1.bar(x + width/2, avg_mpg, width,
label='전체 평균 연비', color='lightgreen')
# 데이터 레이블 추가
def add_labels(bars, values, format_str='{:.1f}'):
for bar, value in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
format_str.format(value),
ha='center', va='bottom')
add_labels(bars1, improvement)
add_labels(bars2, avg_mpg)
# 그래프 꾸미기
plt.title('제조국가별 연비 개선도 분석', pad=20, size=15)
ax1.set_xlabel('제조국')
ax1.set_ylabel('연비 (mpg)')
# x축 레이블 설정
plt.xticks(x, efficiency_improvement['origin'])
# 범례
ax1.legend(loc='upper right')
# 그리드 추가
ax1.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# 시간에 따른 변화를 보여주는 라인 플롯 추가
yearly_data = (
mpg_df.group_by(['origin', 'model_year'])
.agg([
pl.col('mpg').mean().alias('평균_연비')
])
.sort(['origin', 'model_year'])
)
plt.figure(figsize=(12, 6))
# 각 제조국별로 라인 플롯 그리기
for country in yearly_data['origin'].unique():
country_data = yearly_data.filter(pl.col('origin') == country)
plt.plot(country_data['model_year'],
country_data['평균_연비'],
'o-', linewidth=2, label=country, markersize=8)
plt.title('제조국가별 연도별 평균 연비 변화', pad=20, size=15)
plt.xlabel('연도')
plt.ylabel('평균 연비 (mpg)')
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()

11. 고성능 차량 분석 (상위 10% 마력)
high_performance = (
mpg_df.filter(
pl.col('horsepower') >= pl.col('horsepower').quantile(0.9)
)
.group_by('origin')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('weight').mean().alias('평균_중량'),
pl.count().alias('차량_수')
])
.sort('차량_수', descending=True)
)
print("고성능 차량 분석:")
print(high_performance)
high_performance = (
mpg_df.filter(
pl.col('horsepower') >= pl.col('horsepower').quantile(0.9)
)
.group_by('origin')
.agg([
pl.col('mpg').mean().alias('평균_연비'),
pl.col('horsepower').mean().alias('평균_마력'),
pl.col('weight').mean().alias('평균_중량'),
pl.count().alias('차량_수')
])
.sort('차량_수', descending=True)
)
print("고성능 차량 분석:")
print(high_performance)
고성능 차량 분석:
shape: (1, 5)
┌────────┬───────────┬───────────┬───────────┬─────────┐
│ origin ┆ 평균_연비 ┆ 평균_마력 ┆ 평균_중량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════╪═══════════╪═══════════╪═══════════╪═════════╡
│ usa ┆ 13.405 ┆ 186.925 ┆ 4328.7 ┆ 40 │
└────────┴───────────┴───────────┴───────────┴─────────┘
고성능 차량 분석:
shape: (1, 5)
┌────────┬───────────┬───────────┬───────────┬─────────┐
│ origin ┆ 평균_연비 ┆ 평균_마력 ┆ 평균_중량 ┆ 차량_수 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ u32 │
╞════════╪═══════════╪═══════════╪═══════════╪═════════╡
│ usa ┆ 13.405 ┆ 186.925 ┆ 4328.7 ┆ 40 │
└────────┴───────────┴───────────┴───────────┴─────────┘
# 한글 폰트 설정
plt.rc('font', family='NanumGothic')
plt.rcParams['axes.unicode_minus'] = False
# 전체 데이터와 고성능 차량의 특성을 비교하는 그래프를 그리기
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
# 첫 번째 그래프: 평균 연비, 마력, 중량 비교
x = np.arange(3) # 특성의 수
width = 0.35
# 전체 평균 계산
total_avg = mpg_df.select([
pl.col('mpg').mean(),
pl.col('horsepower').mean(),
pl.col('weight').mean()
]).to_numpy().flatten()
# 고성능 차량 평균
high_perf_avg = np.array([
high_performance['평균_연비'][0],
high_performance['평균_마력'][0],
high_performance['평균_중량'][0]/10 # 중량 스케일 조정
])
total_avg[2] = total_avg[2]/10 # 전체 평균 중량도 스케일 조정
# 막대 그래프 그리기
bars1 = ax1.bar(x - width/2, total_avg, width, label='전체 평균', color='lightblue')
bars2 = ax1.bar(x + width/2, high_perf_avg, width, label='고성능 차량 평균', color='lightcoral')
# 그래프 꾸미기
ax1.set_title('전체 차량 vs 고성능 차량 특성 비교', pad=20)
ax1.set_xticks(x)
ax1.set_xticklabels(['연비(mpg)', '마력', '중량(×10kg)'])
ax1.legend()
# 데이터 레이블 추가
for bars in [bars1, bars2]:
for bar in bars:
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.1f}',
ha='center', va='bottom')
# 두 번째 그래프: 고성능 차량 분포
# 원 그래프로 제조국별 비율 표시
total_cars = high_performance['차량_수'].sum()
labels = [f'{origin}\n({count}대, {count/total_cars*100:.1f}%)'
for origin, count in zip(high_performance['origin'], high_performance['차량_수'])]
ax2.pie(high_performance['차량_수'], labels=labels, autopct='%1.1f%%',
colors=['lightblue', 'lightgreen', 'lightcoral'])
ax2.set_title('고성능 차량의 제조국별 분포', pad=20)
plt.tight_layout()
plt.show()
# 한글 폰트 설정
plt.rc('font', family='NanumGothic')
plt.rcParams['axes.unicode_minus'] = False
# 전체 데이터와 고성능 차량의 특성을 비교하는 그래프를 그리기
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
# 첫 번째 그래프: 평균 연비, 마력, 중량 비교
x = np.arange(3) # 특성의 수
width = 0.35
# 전체 평균 계산
total_avg = mpg_df.select([
pl.col('mpg').mean(),
pl.col('horsepower').mean(),
pl.col('weight').mean()
]).to_numpy().flatten()
# 고성능 차량 평균
high_perf_avg = np.array([
high_performance['평균_연비'][0],
high_performance['평균_마력'][0],
high_performance['평균_중량'][0]/10 # 중량 스케일 조정
])
total_avg[2] = total_avg[2]/10 # 전체 평균 중량도 스케일 조정
# 막대 그래프 그리기
bars1 = ax1.bar(x - width/2, total_avg, width, label='전체 평균', color='lightblue')
bars2 = ax1.bar(x + width/2, high_perf_avg, width, label='고성능 차량 평균', color='lightcoral')
# 그래프 꾸미기
ax1.set_title('전체 차량 vs 고성능 차량 특성 비교', pad=20)
ax1.set_xticks(x)
ax1.set_xticklabels(['연비(mpg)', '마력', '중량(×10kg)'])
ax1.legend()
# 데이터 레이블 추가
for bars in [bars1, bars2]:
for bar in bars:
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.1f}',
ha='center', va='bottom')
# 두 번째 그래프: 고성능 차량 분포
# 원 그래프로 제조국별 비율 표시
total_cars = high_performance['차량_수'].sum()
labels = [f'{origin}\n({count}대, {count/total_cars*100:.1f}%)'
for origin, count in zip(high_performance['origin'], high_performance['차량_수'])]
ax2.pie(high_performance['차량_수'], labels=labels, autopct='%1.1f%%',
colors=['lightblue', 'lightgreen', 'lightcoral'])
ax2.set_title('고성능 차량의 제조국별 분포', pad=20)
plt.tight_layout()
plt.show()
12. 종합 통계
summary_stats = {
'전체_차량_수': mpg_df.shape[0],
'평균_연비': round(mpg_df['mpg'].mean(),2),
'평균_마력': round(mpg_df['horsepower'].mean(),2),
'평균_중량': round(mpg_df['weight'].mean(),2),
'최고_연비': mpg_df['mpg'].max(),
'최저_연비': mpg_df['mpg'].min(),
'가장_많은_제조국가': mpg_df['origin'].value_counts().head(1),
'연비_표준편차': round(mpg_df['mpg'].std(),2)
}
print("종합 통계:")
print(summary_stats)
summary_stats = {
'전체_차량_수': mpg_df.shape[0],
'평균_연비': round(mpg_df['mpg'].mean(),2),
'평균_마력': round(mpg_df['horsepower'].mean(),2),
'평균_중량': round(mpg_df['weight'].mean(),2),
'최고_연비': mpg_df['mpg'].max(),
'최저_연비': mpg_df['mpg'].min(),
'가장_많은_제조국가': mpg_df['origin'].value_counts().head(1),
'연비_표준편차': round(mpg_df['mpg'].std(),2)
}
print("종합 통계:")
print(summary_stats)
종합 통계:
{'전체_차량_수': 398, '평균_연비': 23.51, '평균_마력': 104.47, '평균_중량': 2970.42, '최고_연비': 46.6, '최저_연비': 9.0, '가장_많은_제조국가': shape: (1, 2)
┌────────┬───────┐
│ origin ┆ count │
│ --- ┆ --- │
│ str ┆ u32 │
╞════════╪═══════╡
│ europe ┆ 70 │
└────────┴───────┘, '연비_표준편차': 7.82}
종합 통계:
{'전체_차량_수': 398, '평균_연비': 23.51, '평균_마력': 104.47, '평균_중량': 2970.42, '최고_연비': 46.6, '최저_연비': 9.0, '가장_많은_제조국가': shape: (1, 2)
┌────────┬───────┐
│ origin ┆ count │
│ --- ┆ --- │
│ str ┆ u32 │
╞════════╪═══════╡
│ europe ┆ 70 │
└────────┴───────┘, '연비_표준편차': 7.82}