728x90
반응형
Pandas
Pandas는 데이터 분석과 조작에 강력한 도구입니다.
아래와 같은 기능을 제공합니다:
- 행과 열에 라벨 사용 가능
- 기본적인 통계 데이터 제공
- NaN 값을 자동으로 처리
- 숫자와 문자열을 자동으로 로드
- 데이터셋을 병합(Merge) 가능
- NumPy 및 Matplotlib과의 통합 지원
1. Pandas Series 데이터 생성
Pandas의 Series는 1차원 데이터 구조입니다. 라벨과 데이터를 연결하여 데이터를 효과적으로 다룰 수 있습니다.
TIP💡
위와 같이 불러올 단어 한두단어를 누르고 'Tab' 키를 누르면 단축키를 불러올 수 있습니다.
pandas 를 불러오는 방법
import pandas as pd
import pandas as pd
index = ['eggs', 'apples', 'milk', 'bread']
data = [30, 6, 'Yes', 'No']
groceries = pd.Series(data=data, index=index)
print(groceries)
출력
eggs 30
apples 6
milk Yes
bread No
dtype: object
TIP💡 속성 확인하는 방법
groceries.shape
# (4,)
groceries.dtype
# dtype('O')
groceries.size
# 4
groceries.index
# Index(['eggs', 'apples', 'milk', 'bread'], dtype='object')
groceries.values
# [30, 6, 'Yes', 'No']
# 데이터 구조 확인
groceries.ndim
# 1
2. Series의 산술 연산(레이블과 인덱스)
Pandas Series는 벡터화된 연산을 지원하므로 수학적 연산을 각 요소에 빠르게 적용할 수 있습니다.
2-1. Scalar Operations
# 모든 값에 5를 더하기
# 과일이 각각 5개씩 입고 되었다 +5
fruits = fruits + 5
출력
apples 15
oranges 11
bananas 8
dtype: int64
- fruits + 5 : Series의 모든 값에 5를 더합니다.
2-2. Element-wise Operations
# 오렌지만 2개가 팔렸다
fruits['oranges'] = fruits['oranges'] - 2
출력
apples 15
oranges 9
bananas 8
dtype: int64
- 특정 요소에 접근하여 값만 수정할 수 있습니다.
2-3. Mismatched Index Operations
# 다른 Series와 연산
# apples 와 bananas 가 3개씩 더 팔렸습니다.
discount = pd.Series([2, 3], index=['apples', 'bananas'])
출력
apples 12
oranges 9
bananas 5
dtype: int64
- discount와 fruits의 인덱스가 일치하지 않는 경우, 일치하는 인덱스에서만 연산이 수행됩니다.
- 일치하지 않는 인덱스(oranges)는 NaN이 반환됩니다.
3. 실습 : 행성과 거리 계산
3-1. 문제
distance_from_sun = [149.6, 1433.5, 227.9, 108.2, 778.6]
planets = ['Earth', 'Saturn', 'Mars', 'Venus', 'Jupiter']
dist_planets = pd.Series(data=distance_from_sun, index=planets)
time_light = dist_planets / 18 # 빛의 속도(c)로 계산
close_planets = time_light[time_light < 40] # 40분 미만 필터링
다음과 같은 레이블과 값을 가지는 Pandas Series 를 만드세요. 변수는 dist_planets 로 만드세요.
distance_from_sun = [149.6, 1433.5, 227.9, 108.2, 778.6]¶
planets = ['Earth','Saturn', 'Mars','Venus', 'Jupiter']
dist_planets =
3-1. 풀이
dist_planets = pd.Series(index= planets, data= distance_from_sun)
출력
Earth 149.6
Saturn 1433.5
Mars 227.9
Venus 108.2
Jupiter 778.6
dtype: float64
3-2. 문제
거리를 빛의 상수 c( 18 ) 로 나눠서, 가는 시간이 얼마나 걸리는 지 계산하여 저장하세요
time_light =
3-2. 풀이
time_light = dist_planets / 18
time_light < 40
출력
Earth True
Saturn False
Mars True
Venus True
Jupiter False
dtype: bool
3-3. 문제
Boolean indexing을 이용해서 가는 시간이 40분보다 작은것들만 가져오시오.
close_planets =
3-3. 풀이
time_light[time_light < 40 ]
출력
Earth 8.311111
Mars 12.661111
Venus 6.011111
dtype: float64
728x90
반응형
'Python > 이론' 카테고리의 다른 글
110. [Python] [Pandas] 프로그래밍 기본 사항 : Dealing with NaN (0) | 2025.01.22 |
---|---|
109. [Python] [Pandas] 프로그래밍 기본 사항 : Dataframe (0) | 2025.01.22 |
107. [Python] [Pandas] 프로그래밍 기본 사항 : Series Attributes (0) | 2025.01.21 |
106. [Python] 프로그래밍 기본 사항 : NUMPY BASICS (2) | 2025.01.21 |
104. [Python] 프로그래밍 기본 사항 : Random & Datetime (1) | 2025.01.21 |