본문 바로가기
Python

[파이썬] 판다스: 1차 배열, Series

by eyoo 2022. 4. 28.

Pandas 의 장점

  • 열과 행을 위한 라벨이 허용된다.
  • 기본적인 통계데이터가 제공된다.
  • NaN values 를 알아서 처리한다.
  • 숫자 문자열을 알아서 로드한다.
  • 데이터셋들을 merge 할 수 있음.
  • NumPy 와 Matplotlib를 아우른다.

 

판다스를 쓰기위해 우선 pandas를 import한다.

 

import pandas as pd

 

판다스에서 1차원 데이터를 시리즈라고 한다.

 

Series함수를 사용해 시리즈를 생성해보자.

 

in:

my_data = [30, 6, 'Yes', 'No']
x = pd.Series(data= my_data)
x

out:

0     30
1      6
2    Yes
3     No
dtype: object

# Series 함수에 data= 파라미터를 사용해 시리즈를 생성할수있다.

# 시리즈 왼쪽의 숫자들은 인덱스이며 오른쪽 데이터는 밸류라 한다.

 

 

values 함수로 밸류 데이터들을 볼수있다.

 

in:

x.values

out:

array([30, 6, 'Yes', 'No'], dtype=object)

# values 함수와 함께 index 함수로 인덱스가 어떤식으로 이뤄져있는지 확인할수있다.

 

 

index= 파라미터에 인덱스로 쓸 값을 넣어 만들수있다.

 

in:

my_index = ['eggs', 'apples', 'milk', 'bread']
my_data = [30, 6, 'Yes', 'No']
groceries = pd.Series(data= my_data, index= my_index)
groceries

out:

eggs       30
apples      6
milk      Yes
bread      No
dtype: object

# data= 파라미터를 먼저 오게 하자.

 

 

바뀐 인덱스값을 확인할수있다.

 

in:

groceries.index

out:

Index(['eggs', 'apples', 'milk', 'bread'], dtype='object')

 

 

인덱스를 기준으로 밸류를 찾을수 있다.

 

in:

print(groceries['eggs'])
print(groceries[-1])
print(groceries['apples':'milk'])

out:

30
No
apples      6
milk      Yes
dtype: object

# 밸류값으로는 찾을수 없으며 인덱스로 설정된 단어로 슬라이싱 할수있다.

 

 

넘파이때 처럼 직접 연산하여 값을 바꿀수 있다.

 

in:

index = ['apples', 'oranges', 'bananas']
data = [10, 6, 3,]
fruits = pd.Series(data= data, index=index)
fruits = fruits + 5
fruits

out:

apples     15
oranges    11
bananas     8
dtype: int64

 

 

또한 원하는 인덱스의 데이터만 골라서 바꿔줄수도 있다.

 

in:

fruits['oranges'] = fruits['oranges'] - 2 
fruits

out:

apples     15
oranges     9
bananas     8
dtype: int64

 

 

apples와 bananas가 3개씩 더 들어가야 한다면..

 

in:

fruits[['apples','bananas']] = fruits[['apples','bananas']]+3
fruits

out:

apples     18
oranges     9
bananas    11
dtype: int64

댓글