Sign In

Pandas 간단 정리

T
TikaToka
Thanks to Kaggle Learn.
만약에 뭔가 기억이 나지 않는다면, 두가지만 기억하자
help()
dir()
함수 사용법을 알려주거나 어떤 함수가 있는지 알려준다.

Import

import pandas as pd

데이터 만들기

pd.Series([values], index=[index names], name='series name') # 1 column
pd.DataFrame({'key1': [values1], 'key2': [values2]}, index=[index names]) # n column

csv 읽기

pd.read_csv('경로', index_col=int) # index_col은 특정 열을 index로 쓰고 싶을 때 사용

특정 열에 access

review라는 변수에 dataframe이 담겨있고, country라는 열에 접근하려면
review.country[int]
review['country'][int]

indexing

iloc (index based)
review.iloc[0]
review.iloc[:, 0]
loc (label based)
review.loc[:, 'column name'
review.loc[:, [column names]]

index 조작

review.set_inex("title")

조건문

review.country == 'Korea'
# 위를 활용하여
review.loc[reviews.country == 'Korea']
review.loc[(review.country == 'Korea') & (reviews.points >= 90)] # and 불가능
review.loc[(review.country == 'Korea') | (reviews.points >= 90)] # or 불가능

review.loc[review.country.isin(['Italy', 'France'])]
review.loc[review.price.notnull()]

값 변경

reviews['critic'] = 'everyone'

평균

review.score.mean()

고유값

review.country.unique()

고유값들의 개수

review.country.value_counts()

함수 적용

map (각각 행렬값에 대해 적용)
review.score.map(lambda x: x - review.score.mean()) # single value
apply (각각 행에 대해 적용)
def remean_score(row):
  row.score = row.score - review.score.mean()
  return row

review.apply(remean_score, axis='columns') # multi value
### 다른 방법
review_score_mean = review.score.mean()
review.points - review_score_mean

데이터 합치기

reviews.country + " - " + reviews.region_1

그룹화

reviews.groupby('column name')
reviews.groupby([column names])
다만 이걸 하면 idx가 명시한 컬럼들로 바뀐다는 것을 생각해야한다.
초기화 하려면
reviews.reset_index()

정렬

reviews.sort_values(by='column name')
reviews.sort_values(by=[column names])
reviews.sort_values(by='column name', ascending=False)
만약 idx를 기준으로 정렬이 필요하면
review.sort_index()

데이터타입 변경

reviews.score.astype('dtype')

없는 데이터 찾기

country 내에 없는 데이터 찾는 경우
reviews[pd.isnull(reviews.country)]
이를 채우는 방법
reviews.region_2.fillna("value")
reviews.taster_twitter_handle.replace("@kerinokeefe", "@kerino")

컬럼명 변경

reviews.rename(columns={'points': 'score'}) # 이름을 지정
reviews.rename(index={0: 'firstEntry', 1: 'secondEntry'}) # idx를 지정\

컬럼과 idx 명을 동시에 변경

reviews.rename_axis("wines", axis='rows').rename_axis("fields", axis='columns') # axis

합치기

pd.concat([canadian_youtube, british_youtube])
Al
Subscribe to 'All about TIKA'
AI Tech Blog with Curriculum Vitae
Subscribe
👍