PYTHON LIBRARY/Numpy & Pandas 실습

Pandas 실습 문제 : nparray[], loc, iloc, 조건부 기호 &, |, 기초 함수 및 데이터 다루기 복습

신강희 2024. 4. 14. 02:26
728x90

# 기초개념에서 배운것들을 실습문제를 통해서 복습

 

winemag-data-130k-v2.csv 파일을 reviews 로 읽는다.

 

import pandas as pd

 

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


# Unnamed: 0 이런 형태로 컬럼에 올라오는 형태는 인덱스가 컬럼으로 올라온것임

# 그럴땐 index_col= 0 을 사용하여 불러오면 정상적으로 출력됨

와인 리뷰 데이터

 

# 분석을 위해 해당 데이터의 기술 통계 확인

df.describe()

 

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

 

desc = df['description']

desc

0         This tremendous 100% varietal wine hails from ...
1         Ripe aromas of fig, blackberry and cassis are ...
2         Mac Watson honors the memory of a wine once ma...
3         This spent 20 months in 30% new French oak, an...
4         This is the top wine from La Bégude, named aft...
                                ...                        
150925    Many people feel Fiano represents southern Ita...
150926    Offers an intriguing nose with ginger, lime an...
150927    This classic example comes from a cru vineyard...
150928    A perfect salmon shade, with scents of peaches...
150929    More Pinot Grigios should taste like this. A r...
Name: description, Length: 150930, dtype: object

 

문제) first_description 이라는 변수에는, 디스크립션 컬럼의 첫번째 데이터를 저장한다.

 

# df['description'] 디스크립션 열만 가져와서 인덱싱으로 [0]을 해당 컬럼의 첫번째 데이터를 가져와서 저장

first_description = df['description'][0]

 

first_description

'This tremendous 100% varietal wine hails from Oakville and was aged over three years in oak. Juicy red-cherry fruit and a compelling hint of caramel greet the palate, framed by elegant, fine tannins and a subtle minty tone in the background. Balanced and rewarding from start to finish, it has years ahead of it to develop further nuance. Enjoy 2022–2030.'

 

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

 

# 전체데이터중 첫번째 데이터 이므로 iloc를 사용하여 [ 0을 기재하여 첫행을 , 아무것도 기재하지 않았으므로 전체 컬럼 ] 을 호출하여 변수에 저장

first_row = df.iloc[0 , ]

 

first_row

country                                                       US
description    This tremendous 100% varietal wine hails from ...
designation                                    Martha's Vineyard
points                                                        96
price                                                      235.0
province                                              California
region_1                                             Napa Valley
region_2                                                    Napa
variety                                       Cabernet Sauvignon
winery                                                     Heitz
Name: 0, dtype: object

 

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

 

# description 컬럼만 가지고와 .head() 함수를 활용하여 상단에 10개에 데이터만 가지고와서 변수로 저장

irst_descriptions = df['description'].head(10)

 

first_descriptions

0    This tremendous 100% varietal wine hails from ...
1    Ripe aromas of fig, blackberry and cassis are ...
2    Mac Watson honors the memory of a wine once ma...
3    This spent 20 months in 30% new French oak, an...
4    This is the top wine from La Bégude, named aft...
5    Deep, dense and pure from the opening bell, th...
6    Slightly gritty black-fruit aromas include a s...
7    Lush cedary black-fruit aromas are luxe and of...
8    This re-named vineyard was formerly bottled as...
9    The producer sources from two blocks of the vi...
Name: description, dtype: object

 

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

 

# 전체데이터중 1,2,3,5,8 인덱스 전체 컬럼을 불러오는것이므로 loc[ 행 위치에는 필요한 인덱스 , 열 위치는 빈칸으로 전체 컬럼] 을 불러와 변수로 저장

sample_reviews = df.loc[[ 1,2,3,5,8 ], ]

 

sample_reviews

 

문제) df 라는 변수에, 다음 조건을 만족하는 데이터프레임을 저장하시오. 인덱스가 0, 1, 10, 100 인 데이터에서, 컬럼이 country, province, region_1, region_2 인 데이터들만 가져와서 저장하시오.

 

# 전체 데이터에서 특정 행과 특정 열만 가지고와 데이터에 업로드하는 것이므로 df.loc를 사용하는게 효율적

dfw = df.loc[ [0,1,10,100] , ['country','province','region_1','region_2'] ]

 

dfw

 

문제) Italy 에서 만들어진 와인에 대해서 italian_wines 이라는 이름으로 데이터프레임을 만드시오.

 

# 유니크한 개수가 몇개인지 확인법 복습

df['country'].unique()

array(['US', 'Spain', 'France', 'Italy', 'New Zealand', 'Bulgaria',
       'Argentina', 'Australia', 'Portugal', 'Israel', 'South Africa',
       'Greece', 'Chile', 'Morocco', 'Romania', 'Germany', 'Canada',
       'Moldova', 'Hungary', 'Austria', 'Croatia', 'Slovenia', nan,
       'India', 'Turkey', 'Macedonia', 'Lebanon', 'Serbia', 'Uruguay',
       'Switzerland', 'Albania', 'Bosnia and Herzegovina', 'Brazil',
       'Cyprus', 'Lithuania', 'Japan', 'China', 'South Korea', 'Ukraine',
       'England', 'Mexico', 'Georgia', 'Montenegro', 'Luxembourg',
       'Slovakia', 'Czech Republic', 'Egypt', 'Tunisia', 'US-France'],
      dtype=object)

 

# 해당 유니크한 항목들마다 총개수가 몇개인지 세는것 복습

df['country'].value_counts()

country
US                        62397
Italy                     23478
France                    21098
Spain                      8268
Chile                      5816
Argentina                  5631
Portugal                   5322
Australia                  4957
New Zealand                3320
Austria                    3057
Germany                    2452
South Africa               2258
Greece                      884
Israel                      630
Hungary                     231
Canada                      196
Romania                     139
Slovenia                     94
Uruguay                      92
Croatia                      89
Bulgaria                     77
Moldova                      71
Mexico                       63
Turkey                       52
Georgia                      43
Lebanon                      37
Cyprus                       31
Brazil                       25
Macedonia                    16
Serbia                       14
Morocco                      12
England                       9
Luxembourg                    9
Lithuania                     8
India                         8
Czech Republic                6
Ukraine                       5
Switzerland                   4
South Korea                   4
Bosnia and Herzegovina        4
China                         3
Egypt                         3
Slovakia                      3
Tunisia                       2
Albania                       2
Montenegro                    2
Japan                         2
US-France                     1
Name: count, dtype: int64

Italy 소재 와인 리뷰가 23478개 인것을 확인 가능

 

# country 컬럼안에서 Italy와 값이 동일한 행들을 확인

df['country'] == 'Italy'

 

# loc를 활용하여 해당 데이터의 전체 열까지 같이 불러옴

df.loc[df['country'] == 'Italy' , : ]

 

# 이후 변수로 메모리에 업로드

italian_wines = df.loc[df['country'] == 'Italy' , : ]

 

italian_wines

ㄴ 호출시 정상 호출되는것 확인

 

문제) 리뷰점수가 95점 이상이고, Australia와 New Zealand 에서 만들어진 와인에 대한 데이터프레임을 top_oceania_wines 이라는 이름의 변수로 저장.

 

# 95 점 이상

df['points'] >= 95

0          True
1          True
2          True
3          True
4          True
          ...  
150925    False
150926    False
150927    False
150928    False
150929    False
Name: points, Length: 150930, dtype: bool

 

# 오스트레일리아인곳은?

df['country'] == 'Australia'

0         False
1         False
2         False
3         False
4         False
          ...  
150925    False
150926    False
150927    False
150928    False
150929    False
Name: country, Length: 150930, dtype: bool

 

# 뉴질랜드 인곳은?

df['country'] == 'New Zealand'

0         False
1         False
2         False
3         False
4         False
          ...  
150925    False
150926    False
150927    False
150928    False
150929    False
Name: country, Length: 150930, dtype: bool

 

# 한꺼번에 표현하여 오스트레일라이거나 뉴질랜드 인곳은? (조건부 기호 | (or) 사용)

(df['country'] == 'Australia') | (df['country'] == 'New Zealand')

0         False
1         False
2         False
3         False
4         False
          ...  
150925    False
150926    False
150927    False
150928    False
150929    False
Name: country, Length: 150930, dtype: bool

 

# 95점 이상이고 오스트레일리아이면서 뉴질랜드인곳 (조건부 기호 & (and) 까지 같이 사용)

(df['points'] >= 95) & ((df['country'] == 'Australia') | (df['country'] == 'New Zealand'))

0         False
1         False
2         False
3         False
4         False
          ...  
150925    False
150926    False
150927    False
150928    False
150929    False
Length: 150930, dtype: bool

 

# 이제 데이터가 있다는것을 확인 하였으니 해당 데이터위치를 불러와야 한다.

# loc를 활용하여 해당 데이터가있는곳이니 행위치에 기재하고 컬럼은 전체를 불러온다.

# 이때 문구가 너무 길다고 생각되면 상단에 불러온 데이터를 변수로 지정하여 불러와도 되고 전체 문구를 기입해도됨.

 

df.loc[(df['points'] >= 95) & ((df['country'] == 'Australia') | (df['country'] == 'New Zealand')), : ]

 

# 문구가 너무 기니 my_filter 라는 변수로 지정해서 불러와보자.

my_filter = (df['points'] >= 95) & ((df['country'] == 'Australia') | (df['country'] == 'New Zealand'))

df.loc [ my_filter , : ]

ㄴ 이렇게 훨씬 간략하게 호출도 가능

 

다음 실습 문제로 계속

반응형