[Python] Pandas 라이브러리 - DataFrame

2022. 1. 2. 16:58·Python/Module

Pandas는 Python Data Analysis Library의 약자이다.

 

직역하면 파이썬에서 데이터를 분석하기 위해 만들어진 라이브러리라고 할 수 있다.

 

물론 나도 파이썬에서 데이터를 분석 및 처리하기 위해 Pandas를 사용하게 되었고, 그 중에도 DataFrame을 다루는 법에 대해 기초적인 부분을 다뤄보고자 한다.

 


DataFrame

 

판다스에서의 DataFrame은 여러가지 데이터 타입을 처리하여 구성할 수 있다. 예를 들어 List, Dictionary, series, ndarray 등이 있다.

또한 DataFrame은 행과 열로 데이터들을 정리해 표의 형태로 처리하는 자료구조를 의미한다.

 

 


 

DataFrame 생성 방법

 

가장 많이 사용하는 두 가지의 데이터 타입인 List와 dictionary를 이용하여 생성하는 법에 대해 알아보자.

 

1. List를 이용하는 방법

import pandas as pd

List_data = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(List_data)

 

% 결과 %

   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

 

 

2. Dictionary를 이용하는 방법

import pandas as pd

Dictionary_data = {
    'name': ['kim', 'lee', 'bak'],
    'age': [20, 34, 55],
    'weight': [45, 53, 66]
}
index_name = [1, 2, 3]

DataFrame = pd.DataFrame(Dictionary_data, index = index_name)

print(DataFrame)

 

% 결과 %

   name  age  weight
1  kim   20      45
2  lee   34      53
3  bak   55      66

 


 

DataFrame 열, 행으로 보는 법

 

1. 열(Column)별 출력

import pandas as pd

Dictionary_data = {
    'name': ['kim', 'lee', 'bak'],
    'age': [20, 34, 55],
    'weight': [45, 53, 66]
}
index_name = [1, 2, 3]

DataFrame = pd.DataFrame(Dictionary_data, index = index_name)

print(DataFrame['age'])
print(DataFrame.age)

 

% 결과 %

1    20
2    34
3    55
Name: age, dtype: int64
1    20
2    34
3    55
Name: age, dtype: int64

 

 

2. 행(Row)별 출력

 

- 행 출력은 열 출력과는 다르게 loc, iloc 함수를 사용하여 출력해야 함에 유의 !!

 

[1] loc : "index name"으로 조회하는 방식이다.

import pandas as pd

Dictionary_data = {
    'name': ['kim', 'lee', 'bak'],
    'age': [20, 34, 55],
    'weight': [45, 53, 66]
}
index_name = [1, 2, 3]

DataFrame = pd.DataFrame(Dictionary_data, index = index_name)

print(DataFrame.loc[1])
print(DataFrame.loc[2])
print(DataFrame.loc[3])

 

% 결과 %

name      kim
age        20
weight     45
Name: 1, dtype: object
name      lee
age        34
weight     53
Name: 2, dtype: object
name      bak
age        55
weight     66
Name: 3, dtype: object

 


[2] iloc : "index Sequence"로 조회하는 방식이다.

import pandas as pd

Dictionary_data = {
    'name': ['kim', 'lee', 'bak'],
    'age': [20, 34, 55],
    'weight': [45, 53, 66]
}
index_name = [1, 2, 3]

DataFrame = pd.DataFrame(Dictionary_data, index = index_name)

print(DataFrame.iloc[0])
print(DataFrame.iloc[1])
print(DataFrame.iloc[2])


% 결과 %

name      kim
age        20
weight     45
Name: 1, dtype: object
name      lee
age        34
weight     53
Name: 2, dtype: object
name      bak
age        55
weight     66
Name: 3, dtype: object

 


 

DataFrame 수정

 

1. 열(Column) 추가

 

위의 예시에서 City를 Column으로 추가해보도록 하자.

import pandas as pd

Dictionary_data = {
    'name': ['kim', 'lee', 'bak'],
    'age': [20, 34, 55],
    'weight': [45, 53, 66]
}
index_name = [1, 2, 3]

DataFrame = pd.DataFrame(Dictionary_data, index=index_name)
DataFrame_add_col = pd.DataFrame(DataFrame, columns= ['City', 'name', 'age', 'weight'])
print(DataFrame_add_col)

DataFrame_add_col['City'] = ['Seoul', 'Busan', "Incheon"]
print(DataFrame_add_col)



% 결과 %

   City name  age  weight
1   NaN  kim   20      45
2   NaN  lee   34      53
3   NaN  bak   55      66
      City name  age  weight
1    Seoul  kim   20      45
2    Busan  lee   34      53
3  Incheon  bak   55      66

 

2. 행(Row) 추가


행 별 출력할 때와 마찬가지로 loc 메소드를 사용하면 된다. (iloc은 수정하는 경우에만 사용)

import pandas as pd

Dictionary_data = {
    'name': ['kim', 'lee', 'bak'],
    'age': [20, 34, 55],
    'weight': [45, 53, 66]
}
index_name = [1, 2, 3]

DataFrame = pd.DataFrame(Dictionary_data, index=index_name)

DataFrame_add_row = DataFrame.copy()
DataFrame_add_row.loc[4] = ['jeon', 24, 60]

print(DataFrame_add_row)

 

 

% 결과 %

    name  age  weight
1   kim   20      45
2   lee   34      53
3   bak   55      66
4  jeon   24      60

 

 

3. 열, 행 삭제

 

열, 행 삭제는 drop 메소드를 사용하여 삭제한다.

Parameter인 axis는 행이면 '0', 열이면 '1'로 작성하면 된다.

만약 기존 프레임 값을 바꾸고 싶다면 inplace=True 옵션을 설정하여야 한다.

왜냐하면 default값은 그냥 해당 열이나 행이 삭제된 값을 삭제한 Frame을 반환하기 때문이다.

 

import pandas as pd

Dictionary_data = {
    'name': ['kim', 'lee', 'bak'],
    'age': [20, 34, 55],
    'weight': [45, 53, 66]
}
index_name = [1, 2, 3]

DataFrame = pd.DataFrame(Dictionary_data, index=index_name)

DataFrame.drop(1, axis=0, inplace=True)

print(DataFrame)

DataFrame.drop('name', axis=1, inplace=True)

print(DataFrame)

 


% 결과 %

  name  age  weight
2  lee   34      53
3  bak   55      66
   age  weight
2   34      53
3   55      66

 


글을 마무리 하며, 여기까지가 pandas의 DataFrame을 다루는 아주 기초적인 부분이다.

여기서 더 많은 메서드를 알게되고 잘 다루게 된다면 데이터를 표로 정리하는 부분에 있어서는 굉장히 유용하게 사용될 것이라고 생각이 된다.

우리 모두 pandas 고수가 되어보자 :)

'Python > Module' 카테고리의 다른 글

[Python] BeautifulSoup 라이브러리  (4) 2021.12.31
[Python] requests 라이브러리  (0) 2021.12.30
'Python/Module' 카테고리의 다른 글
  • [Python] BeautifulSoup 라이브러리
  • [Python] requests 라이브러리
halfcodx
halfcodx
iOS, Flutter Developer
  • halfcodx
    Mins_Programming
    halfcodx
  • 전체
    오늘
    어제
    • 분류 전체보기 (28)
      • My App (1)
        • NostelgiAlbum (0)
        • Ro_ad (1)
        • Growith (0)
      • Retrospect (2)
      • iOS (9)
        • iOS (6)
        • Swift (2)
      • Python (5)
        • Module (3)
        • Knowledge (2)
      • Flutter (10)
        • Basic Knowledge (10)
        • Implementation (0)
  • 블로그 메뉴

    • Home
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    DART
    티스토리챌린지
    ios combine
    combine 이란
    파이썬
    combine
    Python
    requests
    Flutter
    오블완
  • hELLO· Designed By정상우.v4.10.1
halfcodx
[Python] Pandas 라이브러리 - DataFrame
상단으로

티스토리툴바