본문 바로가기

DataScience/Pandas14

Pandas 시카고 범죄율을 예측 Prophet, error_bad_lines, to_datetime(format), resample 함수의 사용법과, 이 함수를 사용하기 위해 인덱스를 설정하는 방법 시카고 범죄율을 예측해 보자 ( Facebook 의 Prophet 라이브러리 활용 )¶ STEP #0: PROBLEM STATEMENT¶ The Chicago Crime dataset : 2001 ~ 2017. Datasource: 캐글 https://www.kaggle.com/currie32/crimes-in-*chicago* Dataset contains the following columns: ID: Unique identifier for the record. Case Number: The Chicago Police Department RD Number (Records Division Number), which is unique to the incident. Date: Date when the in.. 2023. 1. 3.
Pandas Prophet 라이브러리를 이용한 Time Series 데이터 예측 방법 AVOCADO 가격 예측 (Facebook Prophet )¶ STEP #0: 데이터셋¶ 데이터는 미국의 아보카도 리테일 데이터 입니다. (2018년도 weekly 데이터) 아보카도 거래량과 가격이 나와 있습니다. 컬럼 설명 : Date - The date of the observation AveragePrice - the average price of a single avocado type - conventional or organic year - the year Region - the city or region of the observation Total Volume - Total number of avocados sold 4046 - Total number of avocados with PLU 40.. 2023. 1. 2.
Pandas datetime,datetime64,데이터프레임 날짜 일괄처리 Working with Time Series¶ Dates and Times in Python¶ Native Python dates and times: datetime and dateutil¶ In [1]: from datetime import datetime In [2]: someday = datetime(2022, 5, 11, 15 , 30) In [3]: someday.isoformat() Out[3]: '2022-05-11T15:30:00' In [4]: someday.weekday() Out[4]: 2 In [7]: someday.strftime('%Y년 %m월 %d일') Out[7]: '2022년 05월 11일' In [8]: date_str = &#3.. 2022. 11. 30.
Pandas Tip[1] 문자열 컬럼의 슬라이싱. str 해당 데이터 프레임, 관서명 컬럼의 "서" 부분만 바꾸고 싶다면 어떻게해야될까. names = '서울'+df["관서명"].str.replace("서", "경찰서") ### 혹은 df["관서명"].str[ : -2+1] 이런식으로 슬라이싱도 가능하다. station_names = names.to_list() ### 활용을 위해 리스트로 바꾸어주었다. station_names [out] ['서울중부경찰서', '서울종로경찰서', '서울남대문경찰서', '서울경찰서대문경찰서', '서울혜화경찰서', '서울용산경찰서', '서울성북경찰서', '서울동대문경찰서', '서울마포경찰서', '서울영등포경찰서', '서울성동경찰서', '서울동작경찰서', '서울광진경찰서', '서울경찰서부경찰서', '서울강북경찰서', '서울금천경찰서.. 2022. 11. 30.
Pandas concat(), merge() 여러 데이터 프레임을 하나로 합치는 방법 CONCATENATING AND MERGING¶ Reference: https://pandas.pydata.org/pandas-docs/stable/merging.html In [4]: import pandas as pd In [5]: df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', '.. 2022. 11. 25.
Pandas 데이터프레임 오름차순, 내림차순 정렬 .Sort_values() ,sort_index() SORTING AND ORDERING¶ In [41]: df = pd.DataFrame({'Employee ID':[111, 222, 333, 444], 'Employee Name':['Chanel', 'Steve', 'Mitch', 'Bird'], 'Salary [$/h]':[35, 29, 38, 20], 'Years of Experience':[3, 4 ,9, 1]}) df Out[41]: Employee ID Employee Name Salary [$/h] Years of Experience 0 111 Chanel 35 3 1 222 Steve 29 4 2 333 Mitch 38 9 3.. 2022. 11. 25.
Pandas 사용자 정의 함수사용 .apply(), 판다스내장.str라이브러리 PANDAS OPERATIONS¶ In [2]: import pandas as pd In [3]: df = pd.DataFrame({'Employee ID':[111, 222, 333, 444], 'Employee Name':['Chanel', 'Steve', 'Mitch', 'Bird'], 'Salary [$/h]':[35, 29, 38, 20], 'Years of Experience':[3, 4 ,9, 1]}) df Out[3]: Employee ID Employee Name Salary [$/h] Years of Experience 0 111 Chanel 35 3 1 222 Steve .. 2022. 11. 25.
Pandas 카테고리컬, groupby(), 특정 데이터 가져오기 실습¶ In [1]: import pandas as pd import numpy as np # 책 제목과 작가, 그리고 유저별 별점 데이터가 있다. 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', 'Le.. 2022. 11. 24.
Pandas NaN을 처리하는 전략 dropna(), fillna() Dealing with NaN¶ In [150]: # We create a list of Python dictionaries items2 = [{'bikes': 20, 'pants': 30, 'watches': 35, 'shirts': 15, 'shoes':8, 'suits':45}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5, 'shirts': 2, 'shoes':5, 'suits':7}, {'bikes': 20, 'pants': 30, .. 2022. 11. 24.
Pandas CSV파일불러오기, .describe() 통계, .info()정보 winemag-data-150k-v2.csv 파일을 reviews 로 읽는다. In [1]: import pandas as pd In [ ]: # 파일을 불러올때 필요없는 열을 안보여주는 방법 Unnamed 열을 없애기. In [4]: pd.read_csv('../data/winemag-data_first150k.csv') ##../ => 이전폴더로 이동, 여기서 tap 을 누르면 자동으로 폴더리스트가 보인다 Out[4]: Unnamed: 0 country description designation points price province region_1 region_2 variety winery 0 0 US This tremendous 100% varietal wine hails from .. 2022. 11. 24.
Pandas 행, 열 추가, 데이터 삭제 drop(), rename(), 인덱스 초기화 reset_index(inplace= True) In [66]: [ {'bikes': 20, "pants" : 30, "watches" : 35, "glasses" : 4} ] Out[66]: [{'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4}] In [67]: new_item = [ {'bikes': 20, "pants" : 30, "watches" : 35, "glasses" : 4} ] In [68]: pd.DataFrame(data = new_item, index = ["store 3"]) Out[68]: bikes pants watches glasses store 3 20 30 35 4 In [69]: new.. 2022. 11. 24.
Pandas .iloc[ , ], 데이터 프레임에서 컬럼 만드는 방법 Accessing Elements in Pandas DataFrames¶ In [1]: import pandas as pd In [2]: # We create a list of Python dictionaries items2 = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes': 15, 'pants':5}] In [8]: df = pd.DataFrame(data=items2, index= ["store 1","store 2"]) In [9]: df Out[9]: bikes pants watches glasse.. 2022. 11. 24.