LiJell's 성장기

07. Pandas _ Series, DataFrame 본문

Bigdata/파이썬_Python

07. Pandas _ Series, DataFrame

All_is_LiJell 2022. 1. 1. 15:37
반응형

\# -*- coding: utf-8 -*- modified on Jan 01 2022

""" Created on Mon Dec 20 13:31:24 2021

@author: hanju """

07. Pandas _ Series, DataFrame

import numpy as np
import pandas as pd
from pandas import Series, DataFrame
  • pandas : 2차원 정형데이터(테이블, 표 , 데이터프레임)
  • 기본단위 : Series()
  • 1차원 자료구조
  • 하나의 데이터 타입 허용
Series([1,2,3,4])
s1 = Series([1,2,3,4])
s2 = Series([1,2,3,'4'])

s3= Series([1,2,3,4], index = ['a','b','c','d'])
# a    1
# b    2
# c    3
# d    4

Series(s3, index=['A','B','C','D']) #이미 index가 존재하는 경우

색인 (indexing)

s1[0]      # 1 (차원축소 일어남 >> scalar 값)
s1[0:1]    # 차원 축소 x (Series로 반환)
# 0    1
# dtype: int64
s1[[0,3]]  # 차원 축소 x (Series로 반환)
# 0    1
# 3    4
# dtype: int64

s3['a']
s3[['a','c']]
# a    1
# c    3
# dtype: int64

s3['a':'c'] # 문자의 연속 추출은 마지막 범위 포함
# a    1
# b    2
# c    3
# dtype: int64
s1 > 2
# 0    False
# 1    False
# 2     True
# 3     True
# dtype: bool
s1[s1 > 2]
# 2    3
# 3    4
# dtype: int64

s3.b    # 2 >> key indexing

연산

s1 = Series([1,2,3,4])
s1 + 1 #Series는 됨
# 0    2
# 1    3
# 2    4
# 3    5
# dtype: int64

s4 = Series([10,20,30,40])
s5 = Series([10,20,30,40], index=['c','d','e','f'])
s5

s1 + s4 # 같은 위치 값 끼리 더해짐
# 0    11
# 1    22
# 2    33
# 3    44

s3 + s5
# a     NaN
# b     NaN
# c    13.0
# d    24.0
# e     NaN
# f     NaN
# dtype: float64
# 위치값이 같은 것 끼리 합쳐지지만 서로 없는 key값에 대해서는 더할 수 없어서 
# NaN이 나옴

s3.add(s5) # s3 + s5 와 같음
s3.add(s5, fill_value=0)
# 양쪽 모두 존재하지 않은 key 일 경우
# NA 반환 방지를 위해 fill_value 옵션 사용 적극 추천 (없는 key 위치값에 값을 넣어서)
# s3.add(s5, fill_value=0)
# Out[59]: 
# a     1.0
# b     2.0
# c    13.0
# d    24.0
# e    30.0
# f    40.0
# dtype: float64

s3.sub(s5, fill_value=0) # -연산
s3.mul(s5, fill_value=1) # 곱하기니까 1로 해야지 방지가 됨
s3.div(s5, fill_value=1) # 연산 /

기본 메소드

s1.dtype  # dtype('int64')
s1.index  # RangeIndex(start=0, stop=4, step=1) 인덱스 출력
s1.values # array([1, 2, 3, 4], dtype=int64)  값(value) 출력

s3[['c','d','a','b']] # 색인 사용, 배치 순서 변경
s3.reindex(['c','d','a','b']) # 메소드로 배치 순서 변경

s3.index = ['A','B','C','D']
s3

s3[0] = 10 # 값 수정
s3
'''
A    10
B     2
C     3
D     4
dtype: int64
'''

DataFrame

  • 2차원 자료구조 (행과 열 구조)
  • 생성 (시리즈는 열이다.) 객체에 대한 값들의 Series니까 열인듯?
d1 = {'name': ['smith','will'],'sal' :[900,1800]}
d1



df1 = DataFrame(d1)
df1
#     name   sol
# 0  smith   900
# 1   will  1800

d3 = DataFrame(np.arange(1,7).reshape(2,3), index =['a','b'], columns=['col1','col2','col3'])
d3
#    col1  col2  col3
# a     1     2     3
# b     4     5     6


np.arange(1,7).reshape(2,3)

# array([[1, 2, 3],
#        [4, 5, 6]])

# 색인 (indexing) ***

# 컬럼 선택
d3.col1
# a    1
# b    4
# Name: col1, dtype: int32

d3['col1'] # 위와 동일


# iloc, loc ***
# iloc : positional indexing/ indexlocation
# loc : label indexing/ location
d3
'''
   col1  col2  col3
a     1     2     3
b     4     5     6
'''
d3.iloc[:,0]
# a    1
# b    4
d3.iloc[:,0:3]
#    col1  col2  col3
# a     1     2     3
# b     4     5     6
d3.iloc[:,[0,-1]]
#    col1  col3
# a     1     3
# b     4     6

d3.loc[:,['col1','col3']]
#    col1  col3
# a     1     3
# b     4     6

조건색인 처리

d3.loc[d3.col1 == 1, :] #d3의 col1에서 1인있는 행의 모든 열을 값을 가져와라
#   col1  col2  col3
# a     1     2     3
d3
#    col1  col2  col3
# a     1     2     3
# b     4     5     6

기본 메서드

d3.dtypes # 각 컬럼 별 데이터 타입 확인
d3.index
d3.columns
d3.values

d3.columns = ['A','B','C'] # 컬럼 이름 변경
d3
#    A  B  C
# a  1  2  3
# b  4  5  6

연산

d3 + 10

d4 = DataFrame({'A':[10,40], 'B':[20,30], 'C':[30,80]}, index = ['a','b'])
d4
#     A   B   C
# a  10  20  30
# b  40  30  80
d5 = DataFrame({'A':[10,40], 'B':[20,30]}, index = ['a','b'])
d5
#     A   B
# a  10  20
# b  40  30
d3
#    A  B  C
# a  1  2  3
# b  4  5  6

d3 + d5
#     A   B   C
# a  11  22 NaN
# b  44  35 NaN

d3.add(d5, fill_value=0)
#     A   B    C
# a  11  22  3.0
# b  44  35  6.0
반응형

'Bigdata > 파이썬_Python' 카테고리의 다른 글

09.python_pandas_arithmetic_method  (0) 2022.01.02
08.python_pandas_string_method  (0) 2022.01.02
06.python_str_method  (0) 2021.12.20
05.python_numpy  (0) 2021.12.15
04.python_def_lambda_map  (0) 2021.12.15
Comments