파이썬라이브러리를 활용한 데이터 분석 - Pandas

esc247·2022년 6월 9일
0

Data Analysis

목록 보기
2/10
post-thumbnail

Series

  • 일련의 객체를 담을 수 있는 1차원 배열 같은 자료구조
  • index(색인)이라 하는 배열의 데이터 연관된 이름 가지고 있다.
import pandas as pd
from pandas import Series, DataFrame

obj1= pd.Series([4,7,-5,3])

print(obj1, obj1.values,'\n', obj1.index)

0    4
1    7
2   -5
3    3
dtype: int64 [ 4  7 -5  3] 
RangeIndex(start=0, stop=4, step=1)
import numpy as np
print(obj2[obj2>0])
print(obj2*2)
print(np.exp(obj2))

d    6
b    7
c    3
dtype: int64
d    12
b    14
a   -10
c     6
dtype: int64
d     403.428793
b    1096.633158
a       0.006738
c      20.085537
dtype: float64
print('b' in obj2,'e' in obj2)
True False
  • Series는 산술 연산에서 색인과 라벨을 자동 정렬 (join과 비슷)
  • Series 객체와 색인 모두 name 속성 있다.
print(obj3+obj4)
obj4.name= 'population'
obj4.index.name = 'state'
print(obj4)

Cali           NaN
Ohio       70000.0
Oregon     32000.0
Texas     142000.0
Utah           NaN
dtype: float64
state
Cali          NaN
Ohio      35000.0
Oregon    16000.0
Texas     71000.0
Name: population, dtype: float64

DATAFRAME

  • 스프레드시트 형식의 자료구조, 각 column은 서로 다른 종류의 값 담을 수 있음.
  • row 와 column에 대한 색인 가짐
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
        'year': [2000, 2001, 2002, 2001, 2002, 2003],
        'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
frame = pd.DataFrame(data)
  • head() 메서드로 처음 5개 로우 출력 가능
  • 원하는 순서대로 columns 지정하면 이를 가진 DataFrame 객체 생성
frame.head()

pd.DataFrame(data, columns=['year','state','pop'])

사전에 없는 값 넘기면 NaN
values 속성은 2차원 배열로 반환
색인 객체는 변경 불가
pandas 의 인덱스는 중복되는 값 허용

핵심 기능

재색인

  • reindex, 새로운 색에 맞도록 객체를 새로 생성한다.
obj = pd.Series([4.5,7.2,-5.3,3.6], index = ['d','b', 'a', 'c'])
obj2= obj.reindex(['a','b','c','d','e'])
obj2

a   -5.3
b    7.2
c    3.6
d    4.5
e    NaN
dtype: float64

ffill 메서드롤 이용해 누락된 값을 직전 값으로 채워 넣을 수 있다

obj3 = pd.Series(['blue', 'purple', 'yellow'], index = [0,2,4])
obj3.reindex(range(5),method = 'ffill')

0      blue
1      blue
2    purple
3    purple
4    yellow
dtype: object
  • DataFrame에 대한 reindex는 로우,컬럼 또는 둘 다 변경 가능. 그냥 순서만 전달하면 로우가 재색인
frame = pd.DataFrame(np.arange(9).reshape(3,3),
                     index=['a','c','d'],
                     columns = ['Ohio','Texas','Cali'])
frame2 = frame.reindex(['a','b','c','d'])

삭제

drop() 메소드 사용, 선택한 값들이 삭제된 새로운 객체 얻을 수 있다.

obj = pd.Series(np.arange(5.), index = ['a','b','c','d','e'])
obj.drop(['d','c'])

a    0.0
b    1.0
e    4.0
dtype: float64
  • DataFrame 에서는 로우 컬럼 모두 값 삭제 가능
  • drop 함수에 로우 이름을 넘기면 해당 로우(axis=0) 값 모두 삭제
  • 컬럼 값 삭제 시 axis=1 또는 axis=’columns’ 인자로.
data  = pd.DataFrame(np.arange(16).reshape(4,4),
                     index=['Ohio','Colorado','Utah','New York'],
                     columns = ['one', 'two','three','four'])
data.drop(['Colorado', 'Ohio'])

data.drop('two',axis=1)

크기 또는 형태를 변경하는 함수는 새로운 객체를 반환하는 대신 원본 객체를 변경

obj.drop('c',inplace =True)

a    0.0
b    1.0
d    3.0
e    4.0
dtype: float64
  • inplace 옵션 사용하는 경우 버려지는 값을 모두 삭제.

색인,선택,거르기

라벨 이름으로 슬라이싱하면 시작점,끝점 포함

이름으로 선택시 loc[], 정수로 선택시 iloc[]

산술연산과 데이터 정렬

s1 = pd.Series([7.3,-2.5,3.4,1.5],index = ['a','c','d','e'])

s2 = pd.Series([-2.1,3.6,-1.5,4,3.1], index= ['a','c','e','f','g'])
s1+s2

a    5.2
c    1.1
d    NaN
e    0.0
f    NaN
g    NaN
dtype: float64
  • 서로 겹치는 색인이 없는 경우 데이터는 NA값
  • 서로 다른 색인 가지는 객체간 산술연산에서 존재하지 않는 축의 값을 지정 하고 싶을때 add와 fill_value 사용
df1 =pd.DataFrame(np.arange(12.).reshape((3,4)),
                  columns=list('abcd'))
df2  = pd.DataFrame(np.arange(20.).reshape((4,5)),
                    columns=list('abcde'))
 
df1.add(df2,fill_value=0)
profile
막상 하면 모르니까 일단 하자.

0개의 댓글