본문 바로가기

Aiffel_learning/Data_analysis

2-1. pandas의 기본구조 : series, dataframe

https://pandas.pydata.org/pandas-docs/stable/user_guide/10min.html#basic-data-structures-in-pandas

 

10 minutes to pandas — pandas 2.2.2 documentation

10 minutes to pandas This is a short introduction to pandas, geared mainly for new users. You can see more complex recipes in the Cookbook. Customarily, we import as follows: In [1]: import numpy as np In [2]: import pandas as pd Basic data structures in p

pandas.pydata.org

 

특징

  • NumPy기반에서 개발되어 NumPy를 사용하는 애플리케이션에서 쉽게 사용 가능
  • 축(칼럼)의 이름에 따라 데이터를 정렬할 수 있는 자료 구조
  • 다양한 방식으로 인덱싱(indexing)하여 데이터를 다룰 수 있는 기능
  • 통합된 시계열 기능과 시계열 데이터와 비시계열 데이터를 함께 다룰 수 있는 통합 자료 구조
  • 누락된 데이터 (결측치) 처리 기능
  • 데이터베이스처럼 데이터를 합치고 관계 연산을 수행하는 기능
  • - pandas는 excel표 같이 사용하기 편하게 시각화 됨
    - numpy array로도 데이터 불러올 수는 있는데 사용자 친화적이 않음(but 컴퓨터에 친숙한 양식)
    *주로 데이터에서는 0 = no, 1 = yes로 사용됨

설치

pip install pandas

 

series

- 1차원 배열과 비슷한 자료구조 : 배열형태인 리스트, 튜플, 딕셔너리, NumPy 자료형(정수형, 실수형)으로 만들 수 있음

- 형식이 series여야 작동하는 코드들이 있어서 한번씩 사용되나 주로 dataframe이 쓰임

- 형태 : index value

Series 객체 만들기

# index 지정 안했을 때
ser = pd.Series(['a', 'b', 'c', 3]
>>>
0    a
1    b
2    c
3    3
dtype: object

# index 같이 지정헀을 때
ser2 = pd.Series(['a', 'b', 'c', 3], index=['i','j','k','h'])
>>>
i    a
j    b
k    c
h    3
dtype: object

인덱스 설정

ser.index = ['Jhon', 'Steve', 'Jack', 'Bob']
>>>
Jhon     a
Steve    b
Jack     c
Bob      3
dtype: object

"값이 할당 된" 인덱스 = 딕셔너리!

Country_PhoneNumber = {'Korea': 82, 'America': 1, 'Swiss': 41, 'Italy': 39, 'Japan': 81, 'China': 86, 'Rusia': 7}
ser = pd.Series(Country_PhoneNumber)
>>>
Korea      82
America     1
Swiss      41
Italy      39
Japan      81
China      86
Rusia       7
dtype: int64

ser['Korea']
>>>
82

객체, 인덱스 name 붙이기 ( 객체 name = dataframe의 column name)

ser.name = 'Country_PhoneNumber'
ser.index.name = 'Country_Name'
>>>
Country_Name
Korea      82
America     1
Swiss      41
Italy      39
Japan      81
China      86
Rusia       7
Name: Country_PhoneNumber, dtype: int64

 

dataframe(행,열로 이루어진 표)

- 구조 : 행(row) / 열(column)

- row name = index

- column name = 변수(feature) = series name

                            독립변수 : 제공되는 데이터

                            종속변수 : 예측할 변수

# column name 확인하기
data.columns

 

열 1개 불러올 때 : data['column name'] 으로 불러올 수 있음 -> type = series

열 여러개 불러올 때 **리스트에 넣기** : data[['name1', 'name2] -> 대신 type은 dataframe

series -> dataframe으로 변경 : pd.DataFrame(series)