본문 바로가기

Pandas

Pandas(판다스)로 데이터 핸들링 : 기본 : info(), describe(), value_counts(), head()

반응형

Pandas(판다스)로 데이터 핸들링 : 기본 : info(), describe(), value_counts(), head()


Pandas는 파이썬 데이터 처리를 위해 존재하는 가장 인기 있는 라이브러리입니다.  판다스는 다양한 포맷으로 된 파일을 DataFrame으로 로딩할 수 있는 편리한 API를 제공합니다.

 

가장 많이 API로 read_csv()는 CSV뿐만 아니라 어떤 필드 구분 문자 기반의 파일 포맷도 DataFrame으로 변환이 가능합니다. read_csv()의 인자인 sep에 해당 구분 문자를 입력하면 됩니다. 가령 탭으로 필드가 구분돼 있다는 read_scv('파일명', sep='\t')처럼 쓰면 됩니다. read_csv()에서 sep인자를 생략하면 자동으로 콤마로 할당합니다(sep='.').

 

read_csv()와  read_table()의 가장 큰 차이는 read_table()은 기본 구분자로 탭이 설정되어 있다는 정도입니다. read_fwf()는 Fixed Width로 고정길이 기반의 칼럼 포맷을 DataFrame으로 로딩하기 위한 API입니다.

 


Pandas - Basic Practice

import pandas as pd
from sklearn.datasets import load_iris

iris_data = load_iris()
pandas_DF = pd.DataFrame(data=iris_data.data, columns=['sepal_length','sepal_width','petal_length','petal_width'])

print(pandas_DF)
print(type(pandas_DF))

print(pandas_DF.head(10))
print(pandas_DF.shape)

print(pandas_DF.info())
print(pandas_DF.describe())

print(pandas_DF['sepal_width'].value_counts())

year_feature = pandas_DF['sepal_width']
print(year_feature.head(10))
year_value = pandas_DF['sepal_width'].value_counts()
print(year_value)

print(pandas_DF.columns)

 

#print(pandas_DF)
		country continent  year  lifeExp       pop   gdpPercap
0     Afghanistan      Asia  1952   28.801   8425333  779.445314
1     Afghanistan      Asia  1957   30.332   9240934  820.853030
2     Afghanistan      Asia  1962   31.997  10267083  853.100710
3     Afghanistan      Asia  1967   34.020  11537966  836.197138
4     Afghanistan      Asia  1972   36.088  13079460  739.981106
...           ...       ...   ...      ...       ...         ...
1699     Zimbabwe    Africa  1987   62.351   9216418  706.157306
1700     Zimbabwe    Africa  1992   60.377  10704340  693.420786
1701     Zimbabwe    Africa  1997   46.809  11404948  792.449960
1702     Zimbabwe    Africa  2002   39.989  11926563  672.038623
1703     Zimbabwe    Africa  2007   43.487  12311143  469.709298

[1704 rows x 6 columns]

#print(type(pandas_DF))
<class 'pandas.core.frame.DataFrame'>

#print(pandas_DF.head(10))
       country continent  year  lifeExp       pop   gdpPercap
0  Afghanistan      Asia  1952   28.801   8425333  779.445314
1  Afghanistan      Asia  1957   30.332   9240934  820.853030
2  Afghanistan      Asia  1962   31.997  10267083  853.100710
3  Afghanistan      Asia  1967   34.020  11537966  836.197138
4  Afghanistan      Asia  1972   36.088  13079460  739.981106
5  Afghanistan      Asia  1977   38.438  14880372  786.113360
6  Afghanistan      Asia  1982   39.854  12881816  978.011439
7  Afghanistan      Asia  1987   40.822  13867957  852.395945
8  Afghanistan      Asia  1992   41.674  16317921  649.341395
9  Afghanistan      Asia  1997   41.763  22227415  635.341351

#print(pandas_DF.shape)
(1704, 6)

#print(pandas_DF.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1704 entries, 0 to 1703
Data columns (total 6 columns):
 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   country    1704 non-null   object 
 1   continent  1704 non-null   object 
 2   year       1704 non-null   int64  
 3   lifeExp    1704 non-null   float64
 4   pop        1704 non-null   int64  
 5   gdpPercap  1704 non-null   float64
dtypes: float64(2), int64(2), object(2)
memory usage: 80.0+ KB
None

#print(pandas_DF.describe())
             year      lifeExp           pop      gdpPercap
count  1704.00000  1704.000000  1.704000e+03    1704.000000
mean   1979.50000    59.474439  2.960121e+07    7215.327081
std      17.26533    12.917107  1.061579e+08    9857.454543
min    1952.00000    23.599000  6.001100e+04     241.165877
25%    1965.75000    48.198000  2.793664e+06    1202.060309
50%    1979.50000    60.712500  7.023596e+06    3531.846989
75%    1993.25000    70.845500  1.958522e+07    9325.462346
max    2007.00000    82.603000  1.318683e+09  113523.132900

#print(pandas_DF['year'].value_counts())
2007    142
2002    142
1997    142
1992    142
1987    142
1982    142
1977    142
1972    142
1967    142
1962    142
1957    142
1952    142
Name: year, dtype: int64

#print(year_feature.head(10))
0    1952
1    1957
2    1962
3    1967
4    1972
5    1977
6    1982
7    1987
8    1992
9    1997
Name: year, dtype: int64

#print(year_value)
2007    142
2002    142
1997    142
1992    142
1987    142
1982    142
1977    142
1972    142
1967    142
1962    142
1957    142
1952    142
Name: year, dtype: int64

#print(pandas_DF.columns)
Index(['country', 'continent', 'year', 'lifeExp', 'pop', 'gdpPercap'], dtype='object')

read_csv()는 호출 시 파일명 인자로 들어온 파일을 로딩해 DataFrame객체로 반환합니다.  첫 번째 줄에 있던 칼럼 문자열이 DataFrame의 칼럼으로 할당합니다. 데이터의 Row순으로 0,1,2.....과 같이 순차적으로 표시되어 있습니다. 이것을 Pandas의 Index값이라고 합니다.

 

info()메소드를 통해서 통 데이터 건수와 데이터 타입, Null건수를  알 수 있습니다.

 

describe()은 컬럼별 숫자형 데이터 값의 n-percentile분포도, 평균값, 최댓값, 최솟값을 나타냅니다. 오직 숫자형(int, float..) 칼럼의 분포도만 조사하여 자동으로 object타입의 칼럼은 출력에서 제외합니다.

count는 Not Null인 데이터 건수, mean은 전체 데이터의 평균값, std는 표준편차, min은 최소값, max는 최댓값, 25%는 25 percentile값, 50%는 50 percentile값, 75%는 75 percentile값을 의미합니다.

 

value_counta()는 데이터의 분포도를 확인하는 데 매우 유용한 함수가 됩니다. 중요한 것은 DataFrame의 Index가 0부터 시작하는게 아니고 group화 된 값을 기준으로 된다는 것입니다.

 

columns속성을 사용하면 데이터 프레임의 열 이름을 확인할 수 있습니다.

 

반응형