개발학습일지

[Python] 판다스 시리즈 연산 _더하기, 빼기, 나누기, Boolean indexing (부등호 값 찾기) 본문

Python/Pandas

[Python] 판다스 시리즈 연산 _더하기, 빼기, 나누기, Boolean indexing (부등호 값 찾기)

처카푸 2024. 4. 9. 10:23

판다스 시리즈 연산

_더하기, 빼기 연산 시리즈 데이터

index = ['apples', 'oranges', 'bananas']
data = [10, 6, 3,]
fruits = pd.Series(index=index, data= data)
fruits
>>>
    apples     10
    oranges     6
    bananas     3
    dtype: int64

- 더하기 : 전체 물품이 입고되었다 모든 물품 +5 해주자

fruits = fruits + 5
fruits
>>>
    apples     15
    oranges    11
    bananas     8
    dtype: int64

- 빼기 : 오렌지가 2개 팔렸다 오렌지만 -2 해주자

fruits['oranges'] = fruits['oranges'] -2
fruits
>>>
    apples     15
    oranges     9
    bananas     8
    dtype: int64

- 여러 항목 선택 연산 : 사과랑 바나나가 3개씩 팔렸다 둘다 -3 해주자

fruits[ ['apples', 'bananas'] ] = fruits[ ['apples', 'bananas'] ] -3
fruits
>>>
    apples     12
    oranges     9
    bananas     5
    dtype: int64

 

_나누기, 부등기호 값 찾기 시리즈 데이터 

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)
dist_planets
>>>
    Earth       149.6
    Saturn     1433.5
    Mars        227.9
    Venus       108.2
    Jupiter     778.6
    dtype: float64

- 나누기 : 거리를 빛의 상수 c( 18 ) 로 나눠서, 가는 시간이 얼마나 걸리는 지 계산하여 'time_light = ' 로 저장하자

time_light = dist_planets / 18
time_light
>>>
    Earth       8.311111
    Saturn     79.638889
    Mars       12.661111
    Venus       6.011111
    Jupiter    43.255556
    dtype: float64

- Boolean indexing 부등호 값 찾기 : 가는 시간이 40분보다 작은것들만 가져와서 'close_planets = '에 저장하자

close_planets = time_light[time_light < 40]
close_planets
>>>
    Earth     8.311111
    Mars     12.661111
    Venus     6.011111
    dtype: float64

 

판다스와 넘파이 모두 수식을 입력하면 반복문 필요 없이, 바로 전체 데이터에 계산해준다