pandas data 구조

데이터 분석
공개

2024년 12월 20일

pandas: numpy를 라벨링한거

Series

1차원 배열 구조, 이름과 형식을 가지고 모든 값에 고유한 인덱스를 가짐

import pandas as pd

data1 = pd.Series({'ulala': 1, 'haha': 2}, name='class')
data1
ulala    1
haha     2
Name: class, dtype: int64
data1 = pd.Series({'ulala': 1, 'ulala': 2}, name='class')
data1
ulala    2
Name: class, dtype: int64
data2 = pd.Series([1, 2], name='class')
data2
0    1
1    2
Name: class, dtype: int64

DataFrame

2차원 배열 구조, 각 행은 인덱스를 가지고, 각 열은 이름과 형식을 가짐

Before

데이터를 호출하고, 데이터 내용과 요약 / 통계 정보를 확인해야함

칼럼명이 칼럼 타입을 변경해야할 때도 있음

Pandas 사용 준비

  1. 라이브러리 설치
  2. 라이브러리 호출
import pandas as pd

pd.set_option('display.max_rows', 10)

DataFrame 선언

import numpy as np
dataset = np.array([['kor', 70], ['math', 80]])
# declare df 1
df = pd.DataFrame(dataset, columns=['class', 'score'])
# declare df 2
df = pd.DataFrame([['kor', 70], ['math', 80]], columns=['class', 'score'])
# declare df 3
df = pd.DataFrame({'class': ['kor', 'math'], 'score': [70, 80]})
df
class score
0 kor 70
1 math 80

DataFrame 읽고 저장

# filepath = '../book/data/data.csv'
# data = pd.read_csv(filepath, na_values='NA', encoding='utf8')
# data.to_csv('result.csv', header=True, index=True, encoding='utf8')

DataFrame 출력

from sklearn.datasets import load_iris

iris = load_iris()
iris
{'data': array([[5.1, 3.5, 1.4, 0.2],
        [4.9, 3. , 1.4, 0.2],
        [4.7, 3.2, 1.3, 0.2],
        [4.6, 3.1, 1.5, 0.2],
        [5. , 3.6, 1.4, 0.2],
        [5.4, 3.9, 1.7, 0.4],
        [4.6, 3.4, 1.4, 0.3],
        [5. , 3.4, 1.5, 0.2],
        [4.4, 2.9, 1.4, 0.2],
        [4.9, 3.1, 1.5, 0.1],
        [5.4, 3.7, 1.5, 0.2],
        [4.8, 3.4, 1.6, 0.2],
        [4.8, 3. , 1.4, 0.1],
        [4.3, 3. , 1.1, 0.1],
        [5.8, 4. , 1.2, 0.2],
        [5.7, 4.4, 1.5, 0.4],
        [5.4, 3.9, 1.3, 0.4],
        [5.1, 3.5, 1.4, 0.3],
        [5.7, 3.8, 1.7, 0.3],
        [5.1, 3.8, 1.5, 0.3],
        [5.4, 3.4, 1.7, 0.2],
        [5.1, 3.7, 1.5, 0.4],
        [4.6, 3.6, 1. , 0.2],
        [5.1, 3.3, 1.7, 0.5],
        [4.8, 3.4, 1.9, 0.2],
        [5. , 3. , 1.6, 0.2],
        [5. , 3.4, 1.6, 0.4],
        [5.2, 3.5, 1.5, 0.2],
        [5.2, 3.4, 1.4, 0.2],
        [4.7, 3.2, 1.6, 0.2],
        [4.8, 3.1, 1.6, 0.2],
        [5.4, 3.4, 1.5, 0.4],
        [5.2, 4.1, 1.5, 0.1],
        [5.5, 4.2, 1.4, 0.2],
        [4.9, 3.1, 1.5, 0.2],
        [5. , 3.2, 1.2, 0.2],
        [5.5, 3.5, 1.3, 0.2],
        [4.9, 3.6, 1.4, 0.1],
        [4.4, 3. , 1.3, 0.2],
        [5.1, 3.4, 1.5, 0.2],
        [5. , 3.5, 1.3, 0.3],
        [4.5, 2.3, 1.3, 0.3],
        [4.4, 3.2, 1.3, 0.2],
        [5. , 3.5, 1.6, 0.6],
        [5.1, 3.8, 1.9, 0.4],
        [4.8, 3. , 1.4, 0.3],
        [5.1, 3.8, 1.6, 0.2],
        [4.6, 3.2, 1.4, 0.2],
        [5.3, 3.7, 1.5, 0.2],
        [5. , 3.3, 1.4, 0.2],
        [7. , 3.2, 4.7, 1.4],
        [6.4, 3.2, 4.5, 1.5],
        [6.9, 3.1, 4.9, 1.5],
        [5.5, 2.3, 4. , 1.3],
        [6.5, 2.8, 4.6, 1.5],
        [5.7, 2.8, 4.5, 1.3],
        [6.3, 3.3, 4.7, 1.6],
        [4.9, 2.4, 3.3, 1. ],
        [6.6, 2.9, 4.6, 1.3],
        [5.2, 2.7, 3.9, 1.4],
        [5. , 2. , 3.5, 1. ],
        [5.9, 3. , 4.2, 1.5],
        [6. , 2.2, 4. , 1. ],
        [6.1, 2.9, 4.7, 1.4],
        [5.6, 2.9, 3.6, 1.3],
        [6.7, 3.1, 4.4, 1.4],
        [5.6, 3. , 4.5, 1.5],
        [5.8, 2.7, 4.1, 1. ],
        [6.2, 2.2, 4.5, 1.5],
        [5.6, 2.5, 3.9, 1.1],
        [5.9, 3.2, 4.8, 1.8],
        [6.1, 2.8, 4. , 1.3],
        [6.3, 2.5, 4.9, 1.5],
        [6.1, 2.8, 4.7, 1.2],
        [6.4, 2.9, 4.3, 1.3],
        [6.6, 3. , 4.4, 1.4],
        [6.8, 2.8, 4.8, 1.4],
        [6.7, 3. , 5. , 1.7],
        [6. , 2.9, 4.5, 1.5],
        [5.7, 2.6, 3.5, 1. ],
        [5.5, 2.4, 3.8, 1.1],
        [5.5, 2.4, 3.7, 1. ],
        [5.8, 2.7, 3.9, 1.2],
        [6. , 2.7, 5.1, 1.6],
        [5.4, 3. , 4.5, 1.5],
        [6. , 3.4, 4.5, 1.6],
        [6.7, 3.1, 4.7, 1.5],
        [6.3, 2.3, 4.4, 1.3],
        [5.6, 3. , 4.1, 1.3],
        [5.5, 2.5, 4. , 1.3],
        [5.5, 2.6, 4.4, 1.2],
        [6.1, 3. , 4.6, 1.4],
        [5.8, 2.6, 4. , 1.2],
        [5. , 2.3, 3.3, 1. ],
        [5.6, 2.7, 4.2, 1.3],
        [5.7, 3. , 4.2, 1.2],
        [5.7, 2.9, 4.2, 1.3],
        [6.2, 2.9, 4.3, 1.3],
        [5.1, 2.5, 3. , 1.1],
        [5.7, 2.8, 4.1, 1.3],
        [6.3, 3.3, 6. , 2.5],
        [5.8, 2.7, 5.1, 1.9],
        [7.1, 3. , 5.9, 2.1],
        [6.3, 2.9, 5.6, 1.8],
        [6.5, 3. , 5.8, 2.2],
        [7.6, 3. , 6.6, 2.1],
        [4.9, 2.5, 4.5, 1.7],
        [7.3, 2.9, 6.3, 1.8],
        [6.7, 2.5, 5.8, 1.8],
        [7.2, 3.6, 6.1, 2.5],
        [6.5, 3.2, 5.1, 2. ],
        [6.4, 2.7, 5.3, 1.9],
        [6.8, 3. , 5.5, 2.1],
        [5.7, 2.5, 5. , 2. ],
        [5.8, 2.8, 5.1, 2.4],
        [6.4, 3.2, 5.3, 2.3],
        [6.5, 3. , 5.5, 1.8],
        [7.7, 3.8, 6.7, 2.2],
        [7.7, 2.6, 6.9, 2.3],
        [6. , 2.2, 5. , 1.5],
        [6.9, 3.2, 5.7, 2.3],
        [5.6, 2.8, 4.9, 2. ],
        [7.7, 2.8, 6.7, 2. ],
        [6.3, 2.7, 4.9, 1.8],
        [6.7, 3.3, 5.7, 2.1],
        [7.2, 3.2, 6. , 1.8],
        [6.2, 2.8, 4.8, 1.8],
        [6.1, 3. , 4.9, 1.8],
        [6.4, 2.8, 5.6, 2.1],
        [7.2, 3. , 5.8, 1.6],
        [7.4, 2.8, 6.1, 1.9],
        [7.9, 3.8, 6.4, 2. ],
        [6.4, 2.8, 5.6, 2.2],
        [6.3, 2.8, 5.1, 1.5],
        [6.1, 2.6, 5.6, 1.4],
        [7.7, 3. , 6.1, 2.3],
        [6.3, 3.4, 5.6, 2.4],
        [6.4, 3.1, 5.5, 1.8],
        [6. , 3. , 4.8, 1.8],
        [6.9, 3.1, 5.4, 2.1],
        [6.7, 3.1, 5.6, 2.4],
        [6.9, 3.1, 5.1, 2.3],
        [5.8, 2.7, 5.1, 1.9],
        [6.8, 3.2, 5.9, 2.3],
        [6.7, 3.3, 5.7, 2.5],
        [6.7, 3. , 5.2, 2.3],
        [6.3, 2.5, 5. , 1.9],
        [6.5, 3. , 5.2, 2. ],
        [6.2, 3.4, 5.4, 2.3],
        [5.9, 3. , 5.1, 1.8]]),
 'target': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]),
 'frame': None,
 'target_names': array(['setosa', 'versicolor', 'virginica'], dtype='<U10'),
 'DESCR': '.. _iris_dataset:\n\nIris plants dataset\n--------------------\n\n**Data Set Characteristics:**\n\n:Number of Instances: 150 (50 in each of three classes)\n:Number of Attributes: 4 numeric, predictive attributes and the class\n:Attribute Information:\n    - sepal length in cm\n    - sepal width in cm\n    - petal length in cm\n    - petal width in cm\n    - class:\n            - Iris-Setosa\n            - Iris-Versicolour\n            - Iris-Virginica\n\n:Summary Statistics:\n\n============== ==== ==== ======= ===== ====================\n                Min  Max   Mean    SD   Class Correlation\n============== ==== ==== ======= ===== ====================\nsepal length:   4.3  7.9   5.84   0.83    0.7826\nsepal width:    2.0  4.4   3.05   0.43   -0.4194\npetal length:   1.0  6.9   3.76   1.76    0.9490  (high!)\npetal width:    0.1  2.5   1.20   0.76    0.9565  (high!)\n============== ==== ==== ======= ===== ====================\n\n:Missing Attribute Values: None\n:Class Distribution: 33.3% for each of 3 classes.\n:Creator: R.A. Fisher\n:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\n:Date: July, 1988\n\nThe famous Iris database, first used by Sir R.A. Fisher. The dataset is taken\nfrom Fisher\'s paper. Note that it\'s the same as in R, but not as in the UCI\nMachine Learning Repository, which has two wrong data points.\n\nThis is perhaps the best known database to be found in the\npattern recognition literature.  Fisher\'s paper is a classic in the field and\nis referenced frequently to this day.  (See Duda & Hart, for example.)  The\ndata set contains 3 classes of 50 instances each, where each class refers to a\ntype of iris plant.  One class is linearly separable from the other 2; the\nlatter are NOT linearly separable from each other.\n\n.. dropdown:: References\n\n  - Fisher, R.A. "The use of multiple measurements in taxonomic problems"\n    Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to\n    Mathematical Statistics" (John Wiley, NY, 1950).\n  - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.\n    (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.\n  - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System\n    Structure and Classification Rule for Recognition in Partially Exposed\n    Environments".  IEEE Transactions on Pattern Analysis and Machine\n    Intelligence, Vol. PAMI-2, No. 1, 67-71.\n  - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions\n    on Information Theory, May 1972, 431-433.\n  - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II\n    conceptual clustering system finds 3 classes in the data.\n  - Many, many more ...\n',
 'feature_names': ['sepal length (cm)',
  'sepal width (cm)',
  'petal length (cm)',
  'petal width (cm)'],
 'filename': 'iris.csv',
 'data_module': 'sklearn.datasets.data'}
iris = pd.DataFrame(iris.data, columns=iris.feature_names)
iris
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
... ... ... ... ...
145 6.7 3.0 5.2 2.3
146 6.3 2.5 5.0 1.9
147 6.5 3.0 5.2 2.0
148 6.2 3.4 5.4 2.3
149 5.9 3.0 5.1 1.8

150 rows × 4 columns

iris.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 4 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
dtypes: float64(4)
memory usage: 4.8 KB
iris.describe()
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
count 150.000000 150.000000 150.000000 150.000000
mean 5.843333 3.057333 3.758000 1.199333
std 0.828066 0.435866 1.765298 0.762238
min 4.300000 2.000000 1.000000 0.100000
25% 5.100000 2.800000 1.600000 0.300000
50% 5.800000 3.000000 4.350000 1.300000
75% 6.400000 3.300000 5.100000 1.800000
max 7.900000 4.400000 6.900000 2.500000

sepal length와 petal width의 값의 차이가 크다.

전처리 과정에서 변수 정규화 수행의 근거가 된다.

index / column 명 변경

df.index
RangeIndex(start=0, stop=2, step=1)
list(df.index)
[0, 1]
df.index = ['A', 'B']
df.index
Index(['A', 'B'], dtype='object')
df
class score
A kor 70
B math 80
df.set_index('class', drop=True, append=False, inplace=True)
df
score
class
kor 70
math 80
df.reset_index(drop=False, inplace=True)
df
class score
0 kor 70
1 math 80
iris.columns
Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
       'petal width (cm)'],
      dtype='object')
iris.columns = ['sepal length', 'sepal width', 'petal length', 'petal width']
iris
sepal length sepal width petal length petal width
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
... ... ... ... ...
145 6.7 3.0 5.2 2.3
146 6.3 2.5 5.0 1.9
147 6.5 3.0 5.2 2.0
148 6.2 3.4 5.4 2.3
149 5.9 3.0 5.1 1.8

150 rows × 4 columns

iris.columns = iris.columns.str.replace(' ', '_')
iris
sepal_length sepal_width petal_length petal_width
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
... ... ... ... ...
145 6.7 3.0 5.2 2.3
146 6.3 2.5 5.0 1.9
147 6.5 3.0 5.2 2.0
148 6.2 3.4 5.4 2.3
149 5.9 3.0 5.1 1.8

150 rows × 4 columns

데이터 타입 변경

사용 가능한 타입

  • int
  • float
  • bool
  • datetime
  • category
  • object
iris.dtypes
sepal_length    float64
sepal_width     float64
petal_length    float64
petal_width     float64
dtype: object
iris['sepal_length'] = iris['sepal_length'].astype('int')
iris[['sepal_width', 'petal_length']] = \
iris[['sepal_width', 'petal_length']].astype('int')
iris
sepal_length sepal_width petal_length petal_width
0 5 3 1 0.2
1 4 3 1 0.2
2 4 3 1 0.2
3 4 3 1 0.2
4 5 3 1 0.2
... ... ... ... ...
145 6 3 5 2.3
146 6 2 5 1.9
147 6 3 5 2.0
148 6 3 5 2.3
149 5 3 5 1.8

150 rows × 4 columns

row / coumn 선택 추가 삭제

row 선택

iris[0:4]
sepal_length sepal_width petal_length petal_width
0 5 3 1 0.2
1 4 3 1 0.2
2 4 3 1 0.2
3 4 3 1 0.2

column 선택

Series 형식으로 출력

iris['sepal_length']
0      5
1      4
2      4
3      4
4      5
      ..
145    6
146    6
147    6
148    6
149    5
Name: sepal_length, Length: 150, dtype: int64

DataFrame 형식으로 출력

iris[['sepal_length', 'sepal_width']]
sepal_length sepal_width
0 5 3
1 4 3
2 4 3
3 4 3
4 5 3
... ... ...
145 6 3
146 6 2
147 6 3
148 6 3
149 5 3

150 rows × 2 columns

column, row 선택

iris.loc[0:4, ['sepal_length', 'sepal_width']]
sepal_length sepal_width
0 5 3
1 4 3
2 4 3
3 4 3
4 5 3
iris.iloc[0:4, [1, 2]]
sepal_width petal_length
0 3 1
1 3 1
2 3 1
3 3 1

row 추가

# 방법 1: concat 사용
# df = pd.concat([df, pd.DataFrame([{'class': 'eng', 'score': 90}])], ignore_index=True)

# 방법 2: loc 사용 
df.loc[len(df)] = {'class': 'eng', 'score': 90}
df
class score
0 kor 70
1 math 80
2 eng 90

column 추가

df['yo'] = df['score'] + 10
df
class score yo
0 kor 70 80
1 math 80 90
2 eng 90 100

row 삭제

df.drop(2, inplace=True)
df
class score yo
0 kor 70 80
1 math 80 90

column 삭제

df.drop(columns=['yo'], inplace=True)
df
class score
0 kor 70
1 math 80

조건 선택

iris[(iris['sepal_length'] > 5) & (iris['sepal_width'] < 3)]
sepal_length sepal_width petal_length petal_width
54 6 2 4 1.5
58 6 2 4 1.3
62 6 2 4 1.0
63 6 2 4 1.4
68 6 2 4 1.5
... ... ... ... ...
130 7 2 6 1.9
132 6 2 5 2.2
133 6 2 5 1.5
134 6 2 5 1.4
146 6 2 5 1.9

29 rows × 4 columns

df.loc[df['score'] > 70, '합격'] = 'Pass'
df.loc[df['합격'] != 'Pass', '합격'] = 'Fail'
df
class score 합격
0 kor 70 Fail
1 math 80 Pass
import numpy as np

condition_list = [(df['score'] >= 70), 
                  (df['score'] < 70) & (df['score'] >= 60),
                  (df['score'] < 60)]
grade_list = ['A', 'B', 'C']
df['grade'] = np.select(condition_list, grade_list, default='F')
df
class score 합격 grade
0 kor 70 Fail A
1 math 80 Pass A

결측치 탐색

df.isna().sum()
class    0
score    0
합격       0
grade    0
dtype: int64
df.notna().sum(1) # 행 기준
0    4
1    4
dtype: int64

결측치 제거

# dropna(axis=0, how='any' or 'all', thresh=None, subset=None, inplace=False)
df.dropna()
class score 합격 grade
0 kor 70 Fail A
1 math 80 Pass A

결측치 대체

# fillna(value=None, method=None ('pad', 'ffill', 'backfill', 'bfill'), axis=None, inplace=False, limit=None)
맨 위로