파이썬 라이브러리 code

파이썬 라이브러리 code, 파이썬에서 자료를 처리, 표출하기 위한 라이브러리인 numpy, pandas, matplotlib의 예제를 정리하였습니다.
 


1. numpy

import numpy as np

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

# 2차원 NumPy 배열 생성
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D NumPy Array:\n", arr_2d)

# 0과 1로 이루어진 배열 생성
zeros = np.zeros((3, 3))
ones = np.ones((2, 2))
print("Array of zeros:\n", zeros)
print("Array of ones:\n", ones)

# 특정 범위의 요소를 가진 배열 생성
range_arr = np.arange(10, 20)
print("Array with a range of elements:", range_arr)

# 특정 간격의 배열 생성
interval_arr = np.arange(10, 50, 5)
print("Array with a specific interval:", interval_arr)

# 무작위 값으로 이루어진 배열 생성
random_arr = np.random.rand(5)
print("Random array:", random_arr)

# 기본 배열 연산 (덧셈, 뺄셈, 곱셈)
added_arr = arr + 2
subtracted_arr = arr - 2
multiplied_arr = arr * 2
print("Added array:", added_arr)
print("Subtracted array:", subtracted_arr)
print("Multiplied array:", multiplied_arr)

# 행렬 곱셈
result = np.dot(arr_2d, [[1], [1], [1]])
print("Matrix multiplication result:\n", result)

# 배열 재구성
reshaped_arr = arr.reshape(1, 5)
print("Reshaped array:\n", reshaped_arr)

2. numpy (min, max, argmin, argmax)

import numpy as np

# 단일 배열 예제
array = np.array([1, 2, 3, 4, 5])
print("Single Array:", array)
print("Minimum Value:", np.min(array))
print("Maximum Value:", np.max(array))

# 다차원 배열 예제
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\n2D Array:\n", array_2d)
print("Minimum in each row:", np.min(array_2d, axis=1))
print("Maximum in each column:", np.max(array_2d, axis=0))

# 위치(인덱스) 찾기 예제
array = np.array([10, 20, 5, 35, 25])
print("\nArray for Indexes:", array)
print("Index of Minimum Value:", np.argmin(array))
print("Index of Maximum Value:", np.argmax(array))

3. pandas

import pandas as pd

# 데이터프레임 생성: 딕셔너리에서 데이터프레임 생성
data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "City": ["New York", "Paris", "London"]
}
df = pd.DataFrame(data)
print("DataFrame:\n", df)

# 컬럼 데이터 접근: 데이터프레임의 특정 컬럼에 접근
print("Names:\n", df["Name"])

# 행 데이터 접근: loc과 iloc을 사용하여 행 데이터에 접근
print("First row using loc:\n", df.loc[0])
print("First row using iloc:\n", df.iloc[0])

# 새로운 컬럼 추가: 데이터프레임에 새로운 컬럼 추가
df["Salary"] = [70000, 80000, 90000]
print("DataFrame with new column:\n", df)

# 컬럼 제거: 데이터프레임에서 특정 컬럼 제거
df.drop("Age", axis=1, inplace=True)
print("DataFrame after removing a column:\n", df)

# 데이터 필터링: 특정 조건을 만족하는 데이터 필터링
filtered_df = df[df["Salary"] > 75000]
print("Filtered DataFrame:\n", filtered_df)

# 데이터 그룹화 및 집계: 도시별로 그룹화하고 평균 급여 계산
grouped_df = df.groupby("City").mean()
print("Grouped DataFrame:\n", grouped_df)

# 데이터 값 변경: loc를 사용하여 데이터 값 변경
# 예를 들어, 'Bob'의 'City'를 'Berlin'으로 변경
df.loc[df["Name"] == "Bob", "City"] = "Berlin"
print("DataFrame after updating a value:\n", df)

# 인덱스를 사용하여 데이터 값 변경
# 'Bob'이 있는 행의 인덱스는 1, 'City' 값을 'Berlin'으로 변경
df.loc[1, "City"] = "Berlin"
print("DataFrame after updating a value using index:\n", df)

# CSV 파일 읽기 및 쓰기: 예시로만 제공, 실제 파일은 없음
# df_from_csv = pd.read_csv("example.csv")
# df.to_csv("output.csv", index=False)

4. matplotlib

import matplotlib.pyplot as plt
import numpy as np

# 선 그래프 (Line Plot)
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)')
plt.title("Simple Line Plot")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.legend()
plt.show()

# 산점도 그래프 (Scatter Plot)
x = np.random.rand(50)
y = np.random.rand(50)
plt.figure(figsize=(8, 4))
plt.scatter(x, y)
plt.title("Random Scatter Plot")
plt.xlabel("x")
plt.ylabel("y")
plt.show()

# 막대 그래프 (Bar Plot)
categories = ['Category A', 'Category B', 'Category C']
values = [10, 20, 15]
plt.figure(figsize=(8, 4))
plt.bar(categories, values)
plt.title("Simple Bar Plot")
plt.show()

# 히스토그램 (Histogram)
data = np.random.randn(1000)
plt.figure(figsize=(8, 4))
plt.hist(data, bins=30)
plt.title("Histogram")
plt.show()

# 파이 차트 (Pie Chart)
sizes = [25, 35, 20, 20]
labels = ['Section A', 'Section B', 'Section C', 'Section D']
plt.figure(figsize=(6, 6))
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Pie Chart")
plt.show()

 
복사하셔서 활용하시기 바랍니다.

파이썬 문법 기초 정리
파이썬 기본 문법 code
파이썬 자료구조 code
파이썬 이브러리 code
파이썬 flask를 이용한 홈페이지
이름으로 성별,나이,나라 판단하는 Open API 파이썬 예제

Leave a Comment