Python Data Analysis and Visualization


13. Data Analysis and Visualization

NumPy와 Pandas를 이용한 데이터 분석 (Data Analysis with NumPy and Pandas)

NumPy

NumPy는 다차원 배열을 쉽게 처리할 수 있는 라이브러리입니다. 이를 통해 수치 데이터를 효율적으로 다룰 수 있습니다.

import numpy as np

# NumPy 배열 생성
array = np.array([1, 2, 3, 4, 5])
print(array)

# 배열 연산
array = array * 2
print(array)

# 2차원 배열 생성
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)

# 배열 요소 접근
print(matrix[0, 1])  # 2

# 배열 통계 계산
print(np.mean(matrix))  # 3.5
print(np.sum(matrix))   # 21

Pandas

Pandas는 데이터 프레임(DataFrame)을 사용하여 데이터를 쉽게 조작하고 분석할 수 있는 라이브러리입니다.

import pandas as pd

# 데이터 프레임 생성
data = {
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [25, 30, 35],
    'city': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
print(df)

# 데이터 프레임 정보 확인
print(df.info())

# 데이터 접근
print(df['name'])  # 특정 열
print(df.iloc[1])  # 특정 행

# 통계 정보
print(df.describe())

# 데이터 필터링
filtered_df = df[df['age'] > 30]
print(filtered_df)

Matplotlib와 Seaborn을 이용한 데이터 시각화 (Data Visualization with Matplotlib and Seaborn)

Matplotlib

Matplotlib는 강력한 2D 플로팅 라이브러리로, 다양한 종류의 그래프를 그릴 수 있습니다.

import matplotlib.pyplot as plt

# 데이터 준비
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 18, 16]

# 선 그래프 그리기
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Graph')
plt.show()

# 바 그래프 그리기
plt.bar(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Bar Graph')
plt.show()

# 히스토그램 그리기
data = np.random.randn(1000)
plt.hist(data, bins=30)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()

Seaborn

Seaborn은 Matplotlib를 기반으로 하는 시각화 라이브러리로, 통계 그래프를 그리는 데 유용합니다.

import seaborn as sns

# 샘플 데이터 로드
df = sns.load_dataset('tips')

# 히스토그램
sns.histplot(df['total_bill'], kde=True)
plt.title('Total Bill Histogram')
plt.show()

# 산점도
sns.scatterplot(x='total_bill', y='tip', data=df)
plt.title('Total Bill vs Tip')
plt.show()

# 박스 플롯
sns.boxplot(x='day', y='total_bill', data=df)
plt.title('Total Bill by Day')
plt.show()

위 예제에서 Matplotlib를 사용하여 선 그래프, 바 그래프, 히스토그램을 그렸습니다. Seaborn을 사용하여 히스토그램, 산점도, 박스 플롯을 그렸습니다.

NumPy와 Pandas를 통해 데이터를 효율적으로 분석할 수 있고, Matplotlib와 Seaborn을 사용하여 데이터를 시각적으로 표현할 수 있습니다. 이를 통해 데이터 분석 결과를 쉽게 이해하고 전달할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *