본문 바로가기

Python/Pandas

pandas : Series/Label&Index/NaN


 

Pandas 의 장점

  • Allows the use of labels for rows and columns
  • 기본적인 통계데이터 제공
  • NaN values 를 알아서 처리함.
  • 숫자 문자열을 알아서 로드함.
  • 데이터셋들을 merge 할 수 있음.
  • It integrates with NumPy and Matplotlib

Pandas Series 데이터 생성하기

* 필수암기(pandas의 1차원 데이터를 Series(시리즈)라고 부른다 )



Accessing and Deleting Elements in Pandas Series - 레이블과 인덱스


Arithmetic Operations on Pandas Series


실습

import pandas as pd

1. 다음과 같은 레이블과 값을 가지는 Pandas Series 를 만드세요. 변수는 dist_planets 로 만드세요.

distance_from_sun = [149.6, 1433.5, 227.9, 108.2, 778.6]

planets = ['Earth','Saturn', 'Mars','Venus', 'Jupiter']

dist_planets =

3. 거리를 빛의 상수 c( 18 ) 로 나눠서, 가는 시간이 얼마나 걸리는 지 계산하여 저장하세요.

time_light =

3. Boolean indexing을 이용해서 가는 시간이 40분보다 작은것들만 셀렉트 하세요.

close_planets =

 



Pandas Dataframe

레이블로 생성하기


NaN (Not a Number) 은 해당 항목에 값이 없음을 뜻합니다.


인덱스 및 컬럼 생성하기


Accessing Elements in Pandas DataFrames


 


행과 열의 정보로, 데이터를 가져오는 방법

2. 사람용인 인덱스와 컬럼명으로 데이터를 억세스(가져오는) 방법.
.loc[인덱스,컬럼명]


행과 열의 정보로 데이터를 가져오는 방법

3. 컴퓨터가 자동으로 메기는 인덱스로 , 행과 열을 가져오는 방법. => iloc


 


* 행삭제? 열삭제? => 인덱스 삭제, 컬럼 삭제
drop() 함수를 이용하고, axis 를 설정해주면 된다.


Dealing with NaN


NaN 을 처리하는 전략!

1. 삭제하는 전략.

 



실습

import pandas as pd
import numpy as np

# 각 유저별 별점을 주는것이므로, 1 decimal 로 셋팅.
pd.set_option('precision', 1)

# 책 제목과 작가, 그리고 유저별 별점 데이터가 있다.

books = pd.Series(data = ['Great Expectations', 'Of Mice and Men', 'Romeo and Juliet', 'The Time Machine', 'Alice in Wonderland' ])
authors = pd.Series(data = ['Charles Dickens', 'John Steinbeck', 'William Shakespeare', ' H. G. Wells', 'Lewis Carroll' ])

user_1 = pd.Series(data = [3.2, np.nan ,2.5])
user_2 = pd.Series(data = [5., 1.3, 4.0, 3.8])
user_3 = pd.Series(data = [2.0, 2.3, np.nan, 4])
user_4 = pd.Series(data = [4, 3.5, 4, 5, 4.2])

#  np.nan values 는 해당 유저가 해당 책에는 아직 별점 주지 않은것이다.
# labels: 'Author', 'Book Title', 'User 1', 'User 2', 'User 3', 'User 4'. 
# 아래 그림처럼 나오도록 만든다.


# 1. 딕셔너리를 만들고,    2. 데이터프레임으로 만든 후,    3. nan을  평균값으로 채운다.


실습 예제

winemag-data_first150k.csv 파일을 reviews 로 읽는다.

< 코드 >

import pandas as pd

df = pd.read_csv('data/winemag-data_first150k.csv')

df

 

< 결과 >

inplace= True <<<< 이걸해야 저장이 된다.


리뷰의 디스크립션 컬럼을 desc 로 저장한다.



first_row 라는 변수에, 첫번째 리뷰 데이터(행)를 저장한다.


first_row 라는 변수에, 첫번째 리뷰 데이터(행)를 저장한다.

 


리뷰의 description column 의 값들 중, 첫번째부터 10번째 데이터까지를 first_descriptions 변수에 저장한다.


★★리뷰에서 인덱스가 1, 2, 3, 5, 8 인 데이터를, sample_reviews 변수에 저장한다