본문 바로가기

DataScience/Python15

Pandas (영화 추천 시스템)pivot_table 함수 사용법, item based collacborative filtering 을 하기 위해, corr() 함수를 이용한 correlation과min_periods 파라미터 사용법 영화 추천 시스템¶ PROBLEM STATEMENT¶ 추천시스템은 영화나 노래등을 추천하는데 사용되며, 주로 관심사나 이용 내역을 기반으로 추천한다. 이 노트북에서는, Item-based Collaborative Filtering 으로 추천시스템을 구현한다. Dataset MovieLens: https://grouplens.org/datasets/movielens/100k/ STEP #0: LIBRARIES IMPORT¶ In [23]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline In [24]: from google.colab import drive.. 2023. 1. 3.
파이썬 원본 폴더에 이미지 파일 여러개를 일정비율로 나눠서, 랜덤으로 파일의 순서를 바꾼다음, 새로운폴더를 생성하여 넣는 방법 환경 : 리눅스 ( 윈도우도 됨) PetImages 라는 원본폴더 안에 Cat 폴더 안에는 고양이 사진이 12500장 Dog 폴더 안에는 개사진이 12500장 있다고 해보자 새로운 cats-v-dogs 라는 폴더를 생성하고 그안에 testing 폴더, training 폴더를 생성 testing 안에 cats, dogs training 안에 cats, dogs 폴더를 생성한다음 원본에 있는 사진을 일정 비율로 나눠서 (예를들면 9대1로 나누면 11250장, 1250장) testing 안에 cats 폴더에 1250장 testing 안에 dogs 폴더에 1250장 training 안에 cats 폴더에 11250장 training 안에 dogs 폴더에 11250장 이렇게 옮길것이다. 1.필요한 라이브러리를 임포.. 2022. 12. 30.
이미지 url을 가져올때 없는 이미지인지 체크하는 방법 이미지인지 체크하는 가장 쉬운방법은 해당 파일의 확장자를 보면됩니다 하지만 url 이미지 같은경우는 변수가 발생합니다 때문에 아래와같은 절차를 따릅니다. # Content-Type 헤더 확인: # URL이 이미지를 가리키는지 나타내는지 확인하는 것입니다. # 다음은 if 문을 사용하여 이를 수행하는 방법의 예입니다. import requests r = requests.get(url) if r.headers['Content-Type'].startswith('image'): print("This is an image URL.") else: print("This is not an image URL.") [out]This is not an image URL. 2022. 12. 23.
파이썬 차트 라이브러리 추천 plotly (커스터 마이징이 좋다) 파이썬 차트를 그리는 라이브러리는 matplotlib , seaborn 가 보편적이지만 인터랙티브하게 만들거나 커스터마이징을 하려면 꽤나 머리가 아프다 그래서 plotly 를 사용하면 보다 나은 차트를 구현 할 수 있다. https://plotly.com/python/ 다음 코드는 아래 차트를 그리는 예시이다. fig = make_subplots(rows=2, cols=2,subplot_titles=last_df.columns[1:]) fig.add_trace( go.Scatter(x=last_df['index'], y=last_df['Score'],name="Score", mode="markers+text", text=last_df['index'].values, # text=["Text A", "Tex.. 2022. 12. 23.
두 개의 데이터 프레임을 서브 플롯으로 배치해보자 fig, ax = plt.subplots(1, 2) df1['Win %'].plot(ax=ax[0]) hero.plot(ax=ax[1]) ax[0].set_title('Data Frame 1') ax[0].set_xlabel('X Axis') ax[0].set_ylabel('Y Axis') ax[1].set_title('Data Frame 2') ax[1].set_xlabel('X Axis') ax[1].set_ylabel('Y Axis') ax[1].legend() plt.show() 2022. 12. 22.
Streamlit 이미지 크기를 조절하기 서론 : 스트림릿 대쉬보드는 데이터 분석용으로 이미지 처리 기능이 내장되어있지 않기때문에 아래와 같은 단계를 따릅니다. steps: 1. 먼저 이미지 처리 및 조작 기능을 제공하는 Pillow 라이브러리를 설치합니다. Python 패키지 관리자인 pip를 사용하여 Pillow를 설치할 수 있습니다. pip install pillow 2. 다음으로 Streamlet 함수의 Pillow에서 필요한 모듈을 가져옵니다. from PIL import Image 3. 'requests' 라이브러리를 사용하여 URL에서 이미지 데이터를 읽습니다. import requests url = 'https://example.com/image.jpg' response = requests.get(url) image_data = .. 2022. 12. 22.
Pandas 행과 열의 문자열인덱스를 숫자로 가져오는 방법 # pandas 문자열로 된 인덱스를 숫자로 가져오는방법 # Create a sample dataframe df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, index=['a', 'b', 'c']) # Find the index number of label 'b' index_number = df.index.get_loc('b') print(index_number) # Output: 1 # pandas 문자열로 된 컬럼을 숫자로 가져오는방법 # Create a sample dataframe df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) # Find the ind.. 2022. 12. 16.
문자열로 이루어진 리스트를 피클로 저장할때 import pickle # 저장할때 open("파일명", "wb") wb == 바이너리로 저장 # dump(변수명, f) with open("list.pickle","wb") as f: pickle.dump(flattened_list, f) # 로드할때 open("경로명", "rb) rb == 리드 바이너리 with open("data/list.pickle", "rb") as f: flattened_list = pickle.load(f) 2022. 12. 15.
Python gif 파일 만들기 path 경로에 0~3 까지 번호를 지정한 사진을 넣었다. 크기가 좀안맞긴 하다 import os from PIL import Image from IPython.display import Image as Img from IPython.display import display def generate_gif(path): # os.listdir 경로에 파일을 리스트로 반환한다. img_list = os.listdir(path) img_list = [path + '/' + x for x in img_list] images = [Image.open(x) for x in img_list] im = images[0] im.save('out.gif', save_all=True, append_images=images[1.. 2022. 12. 12.
Pandas url.csv 데이터분석 6.a실습 PYTHON PROGRAMMING¶ In [1]: # 한글 찍기 import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb %matplotlib inline import platform from matplotlib import font_manager, rc plt.rcParams['axes.unicode_minus'] = False if platform.system() == 'Darwin': rc('font', family='AppleGothic') elif platform.system() == 'Windows': path = ".. 2022. 11. 29.
데이터프레임에 "특정단어"가 들어가있는지 여부 pd.str.contains() 데이터 중 choice_description 값에 Vegetables 들어가지 않는 경우의 갯수를 출력하라 df.loc[ df["choice_description"].str.contains("Vegetables", case =False) == False, ] 혹은, df.loc[ ~df["choice_description"].str.contains("Vegetables",case =False), ] # case = False = 대문자 , 소문자 상관없이 가져와라 2022. 11. 29.
pd.read_csv(thousands= ','), 차원이 다른 데이터를 차트로, 데이터프레임에서 데이터값의 콤마제거 해당 데이터 프레임에서 0세부터 100세 까지 나이대 별로 몇명이 있는지 시각화를 한다면 df2 = df.loc[ df["행정구역"].str.contains("삼청동"), "2019년07월_계_0세" : ].values # values 로 컬럼을 제외한 값만 가져온다. [in]df2 [out]array([[ 7, 9, 13, 12, 11, 11, 9, 11, 20, 18, 18, 23, 23, 19, 17, 16, 20, 25, 25, 27, 22, 35, 34, 29, 42, 38, 38, 32, 31, 36, 53, 32, 29, 42, 45, 29, 45, 50, 45, 52, 43, 36, 34, 29, 35, 33, 41, 37, 46, 48, 44, 47, 33, 46, 41, 40, 44, .. 2022. 11. 29.