1. Getting
- dir, shape, columns, info, dtype, iloc
# 롤 랭킹 데이터 : https://www.kaggle.com/datasnaek/league-of-legends
# DataUrl = ‘https://raw.githubusercontent.com/Datamanim/pandas/main/lol.csv’
import pandas as pd
### ###
### 01 Getting & Knowing Data ###
### ###
# 데이터 로드, 데이터는 \t을 기준으로 구분
df = pd.read_csv("https://raw.githubusercontent.com/Datamanim/pandas/main/lol.csv", sep="\t")
# 제공 메소드 확인
dir(df)
help(df)
# 데이터의 행과 열의 갯수
df.shape
# (51490, 61) -> tuple
# 컬럼 확인
df.columns[2:6]
# 데이터 타입 확인
df.info()
df['creationTime'].dtype
# dtype('int64')
df[df.columns[1]].dtype
# dtype('int64')
# 3번째 컬림의 4번째 값
df[df.columns[2]][3] # 인덱스는 0부터 시작
df.iloc[3,2] # [행, 열]
- isnull, describe, unique
# 데이터 로드, 한글데이터(utf-8 > cp949 > euc-kr > latin)
df_kr = pd.read_csv("https://raw.githubusercontent.com/Datamanim/pandas/main/Jeju.csv", encoding='euc-kr')
# 3번째 컬럼의 10~20번째 값
df_kr.iloc[10:20,4]
# 수치형 변수(int64, float64)를 가진 컬럼을 출력
df_kr.select_dtypes(include=[int, float], exclude=object).columns # (include, exclude)
# 각 컬럼의 null 값의 수를 파악
df_kr.isnull().sum()
# 수치형변수의 분포(사분위, 평균, 표준편차, 최대, 최소)를 확인
df_kr.describe()
# 읍면동명의 유일 값을 출력 (series)
df_kr['읍면동명'].unique()
2. Filtering & Sorting
- 컬럼값 필터링, 새로운 컬럼추가, 컬럼값 대치
import pandas as pd
### ###
### 02 Filtering & Sorting ###
### ###
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/pandas/main/chipo.csv')
# quantitiy컬럼의 값이 3인 데이터만 첫 5행을 출력
df.loc[df.quantity == 3]
# quantity, item_price 두개의 컬럼으로 구성된 새로운 데이터프레임을 정의
# copy() 독립적인 복사본으로, 원본 데이터프레임에 영향을 주지 않음
df_new = df[['quantity', 'item_price']].copy()
# item_price 컬럼의 달러표시를 제거하고 float타입으로 저장하여 new_price 컬럼에 저장
# str은 문자열 함수 사용하기 위해
df.loc[:, 'new_price'] = df['item_price'].str.replace('$', '').astype(float)
# new_price 컬럼이 5이하의 값을 가지는 데이터 프레임 추출
df.loc[df['new_price'] < 5]
# 전체 갯수
len(df.loc[df['new_price'] < 5 ])
df.loc[df['new_price'] < 5 ].shape[0]
# 다중조건, new_price값이 9이하이고 item_name값이 'Chicken Salad Bowl'인 데이터프레임 추출
df.loc[(df['new_price'] < 9) & (df['item_name'] == 'Chicken Salad Bowl')]
# (Like) item_name 컬럼 값중 'Chips' 포함하는 경우의 데이터 추출
df.loc[df['item_name'].str.contains('Chips')]
# 'Chips'를 포함하지 않는 경우의 데이터 추출
df.loc[~df['item_name'].str.contains('Chips')]
# item_name 기준으로 중복행이 있으면 첫번째 케이스만 남기기
df.loc[df['item_name'].str.contains('Chips')].drop_duplicates('item_name')
# 마지막 케이스만 남기기
df.loc[df['item_name'].str.contains('Chips')].drop_duplicates('item_name', keep='last')
# item_name 값이 Izze데이터를 Fizzy Lizzy로 수정
df.loc[df['item_name'] == 'Izze', 'item_name'] = 'Fizzy Lizzy'
# choice_description 값이 NaN인 데이터를 'NoData' 값으로 대체
# 두 코드가 비슷하게 동작하지만, 첫 번째 코드는 조건에 맞는 부분만 수정하고, 두 번째 코드는 전체 열을 대체합니다.
df.loc[df['choice_description'].isnull(), 'choice_description'] = 'NoData' #DataFrame
df.loc[:'choice_description'] = df['choice_description'].fillna('NoData') #Series
# item_name의 문자열이 15이상인 데이터를 인덱싱
df.loc[df['item_name'].str.len() >= 15]
# new_price 값이 lst에 해당하는 경우의 데이터 프레임을 추출
lst =[1.69, 2.39, 3.39, 4.45, 9.25, 10.98, 11.75, 16.98]
df.loc[df['new_price'].isin(lst)]
# new_price 컬럼 값에 따라 오름차순으로 정리
df.sort_values('new_price')
# 내림차순
df.sort_values('new_price', ascending=False)
3.Grouping
- value_counts, groupby agg, groupby size
import pandas as pd
### ###
### 03 Grouping ###
### ###
df= pd.read_csv(
'https://raw.githubusercontent.com/Datamanim/pandas/main/AB_NYC_2019.csv'
)
# 데이터의 각 host_name의 빈도수를 구하고 host_name으로 정렬하여 상위 5개를 출력하라 ( 내림차순 )
df['host_name'].value_counts().head(5)
# 오름차순
df['host_name'].value_counts().sort_values(ascending=True).head(5)
# 데이터의 각 host_name의 빈도수를 구하고 빈도수 기준 내림차순 정렬한 데이터 프레임을 만들어라
# 빈도수 컬럼은 counts로 명명하라
df['host_name'].value_counts().to_frame().rename(columns={'host_name': 'counts'})
# neighbourhood_group의 값에 따른 neighbourhood컬럼 값의 갯수를 구하여라
# 두개의 컬럼을 가져올 때는 DataFrame 이여야 한다.
df[['neighbourhood_group', 'neighbourhood']] \
.groupby(['neighbourhood_group', 'neighbourhood'], as_index=False) \
.size()
# neighbourhood_group 값에 따른 price 최대, 최소 값을 구하여라
df[['neighbourhood_group','price']] \
.groupby('neighbourhood_group') \
.agg(['max', 'min'])
# neighbourhood_group 값이 Queens값을 가지는 데이터들 중
# neighbourhood 그룹별로 price값의 최대, 최소값을 구하라
df.loc[df['neighbourhood_group']=='Queens'] \
.groupby('neighbourhood_group')['price'] \
.agg(['max', 'min'])
'Programming > Python' 카테고리의 다른 글
Python - io.BytesIO 예제 (0) | 2024.10.19 |
---|---|
Python - Pandas 예제2 (Apply,Map,Time) (0) | 2024.09.21 |
Python - Pandas 기본 (0) | 2024.09.18 |
Python - AWS Athena 쿼리실행방법 PyAthena vs Boto3 (0) | 2024.09.03 |
Python - Transpose(전치) 예제 (0) | 2024.08.25 |