Python 2021. 6. 2. 17:30
bins = list(range(0, 100, 10))
bins_label = [str(x)+"~"+str(x+10) for x in bins]
df["labels"] = pd.cut(df['value'], bins, right=False, labels=bins_label[:-1])
posted by 초코렛과자
:
Python 2021. 5. 24. 13:23
pd.read_csv('file',thousands=r',')

'Python' 카테고리의 다른 글

dataframe column에서 특정 단어 포함된 row 제외  (0) 2021.06.07
dataframe 범위별 구간 만들기  (0) 2021.06.02
plotly를 이용한 pca  (0) 2021.05.18
dataframe zero value column remove  (0) 2021.05.09
dataframe merge - reduce 이용  (0) 2021.04.22
posted by 초코렛과자
:
Python 2021. 5. 18. 09:46

https://plotly.com/python/pca-visualization/

 

PCA Visualization

Visualize Principle Component Analysis (PCA) of your high-dimensional data in Python with Plotly.

plotly.com

여기에 잘 나와있다. matplotlib를 이용하는것보다 훨씬 코드가 간단해진다.

 

2D

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

df = pd.read_csv("")
pca_df = StandardScaler().fit_transform(df)

pca = PCA(n_components=2)
principalComponents = pca.fit_transform(pca_df)
fig = px.scatter(principalComponents, x=0, y=1, color=df['label'])
fig.show()

3D

pca = PCA(n_components=3)
components = pca.fit_transform(df)

total_var = pca.explained_variance_ratio_.sum() * 100

fig = px.scatter_3d(
    components, x=0, y=1, z=2, color=df['label'],
    title=f'Total Explained Variance: {total_var:.2f}%',
    labels={'0': 'PC 1', '1': 'PC 2', '2': 'PC 3'}
)
fig.show()

'Python' 카테고리의 다른 글

dataframe 범위별 구간 만들기  (0) 2021.06.02
pandas read csv시 thousand 숫자형으로 읽기  (0) 2021.05.24
dataframe zero value column remove  (0) 2021.05.09
dataframe merge - reduce 이용  (0) 2021.04.22
seaborn boxplot 그리기  (0) 2021.04.13
posted by 초코렛과자
:
Python 2021. 5. 9. 14:01
df.loc[:, (df != 0).any(axis=0)]

'Python' 카테고리의 다른 글

pandas read csv시 thousand 숫자형으로 읽기  (0) 2021.05.24
plotly를 이용한 pca  (0) 2021.05.18
dataframe merge - reduce 이용  (0) 2021.04.22
seaborn boxplot 그리기  (0) 2021.04.13
[python] pandas dataframe append  (0) 2020.09.06
posted by 초코렛과자
:
Python 2021. 4. 22. 14:18
import pandas as pd
from functools import reduce
dfs = [df0, df1, df2, dfN]
df_final = reduce(lambda left,right: pd.merge(left,right,on='key'), dfs)

기록

'Python' 카테고리의 다른 글

plotly를 이용한 pca  (0) 2021.05.18
dataframe zero value column remove  (0) 2021.05.09
seaborn boxplot 그리기  (0) 2021.04.13
[python] pandas dataframe append  (0) 2020.09.06
Naver API를 이용한 쇼핑 최저가 검색  (0) 2020.06.09
posted by 초코렛과자
:
Python 2021. 4. 13. 12:29
import seaborn as sns
sns.set(rc={'figure.figsize':(15,5)}) # figsize 지정

# 한글폰트 설정
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fm.get_fontconfig_fonts()
font_location = 'C:/Windows/Fonts/malgunbd.ttf'
font_name = fm.FontProperties(fname=font_location).get_name()
plt.rc('font', family=font_name)
# 한글폰트 설정

plt.xticks(rotation = - 45 ) # xticks rotation
sns.boxplot(data=DPS_data) # draw box plot

 

 매번 까먹어서 기록

posted by 초코렛과자
:
Python 2020. 9. 6. 19:00

dataframe row append 코드

df = pd.DataFrame(columns=['col1','col2','col3'])
data = [1,2,3]
df = df.append(pd.Series(data,index=df.columns), ignore_index=True)
print(df)
#  col1 col2 col3
#0    1    2    3

 

'Python' 카테고리의 다른 글

dataframe merge - reduce 이용  (0) 2021.04.22
seaborn boxplot 그리기  (0) 2021.04.13
Naver API를 이용한 쇼핑 최저가 검색  (0) 2020.06.09
pyinstaller를 이용한 python exe 만들기  (0) 2020.05.28
[python] PCA  (0) 2020.04.09
posted by 초코렛과자
:
Python 2020. 6. 9. 22:18

https://github.com/hongsh87/naver_shopping_minimum_price/blob/master/minibot.py

 

hongsh87/naver_shopping_minimum_price

naver shopping minimum price search and create csv file - hongsh87/naver_shopping_minimum_price

github.com

친한형 부탁으로 네이버 쇼핑에서 최저가를 찾아주는 간단한 bot을 하나 만들었다.

Naver Api를 발급 받아서 넣고 돌리면 위와 같은 간단한 UI가 실행 되면서 최저가를 찾아준다.

'Python' 카테고리의 다른 글

seaborn boxplot 그리기  (0) 2021.04.13
[python] pandas dataframe append  (0) 2020.09.06
pyinstaller를 이용한 python exe 만들기  (0) 2020.05.28
[python] PCA  (0) 2020.04.09
Pandas Big Data 다루기  (0) 2020.03.18
posted by 초코렛과자
:
Python 2020. 5. 28. 22:20

pyinstaller를 이용하면 간단하게 py 파일을 exe 형태로 뽑을 수 있다.

pip install pyinstaller로 설치 후 

pyinstaller 파일명.py 하면 exe파일 생성. library를 다 끌고 와서 용량은 좀 크다.

 

다만 이번에 하면서 에러가 생겼었는데, 해결방법

 

1. 첫번째 에러는 아래와 같은 에러가 났었다.

RecursionError: maximum recursion depth exceeded in comparison

최대심도 에러? 라는 것이라는데 해결방법은

pyinstaller 파일명.py 명령어를 수행하고 나면 해당 폴더에

파일명.spec 이라는 파일이 생기는데 거기 제일 위에 아래와 같이 입력해 준 후 설치하면 됨.

import sys 
sys.setrecursionlimit(10000)

2. exe 파일이 생겼으나, pkg_resources.py2_warn 모듈이 없다는 메시지가 콘솔창에 나옴

마찬가지로 파일명.spec 파일을 열어서 hiddenimports 라는 곳에 pkg_resources.py2_warn를 입력해 주면된다.

a = Analysis(['file.py'],
             pathex=['path'],
             binaries=[],
             datas=[],
             hiddenimports=['pkg_resources.py2_warn'],

 

위와 같이 진행 후 pyinstaller 파일명.spec 으로 실행 하면 exe 생성완료

 

 

'Python' 카테고리의 다른 글

[python] pandas dataframe append  (0) 2020.09.06
Naver API를 이용한 쇼핑 최저가 검색  (0) 2020.06.09
[python] PCA  (0) 2020.04.09
Pandas Big Data 다루기  (0) 2020.03.18
ValueError: If using all scalar values, you must pass an index  (0) 2020.03.09
posted by 초코렛과자
:
Python 2020. 4. 9. 21:46

차원 축소 및 주성분 분석을 위해 많이 사용하는 PCA

자꾸 코드를 까먹어서 기억을 위해 적어둠

----------------------------------------9/3 코드가 너무 엉망이여서 수정

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

df = pd.read_csv('') # read file
# pca는 꼭 표준화를 시켜준다
pca_df = StandardScaler().fit_transform(df)

# 2차원 
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(pca_df)
principalDf = pd.DataFrame(data = principalComponents
             , columns = ['principal component 1', 'principal component 2'])
finalDF = pd.concat([principalDF, df[input y column name]], axis=1)
# pca 그리기
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,1,1) 
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_title('2 component PCA', fontsize = 20)
targets = [0, 1] # y class에 맞춰서 변경
colors = ['r', 'g'] # targets 길이와 같이 color 입력
for target, color in zip(targets,colors):
    indicesToKeep = finalDf[y column name] == target
    ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
               , finalDf.loc[indicesToKeep, 'principal component 2']
               , c = color
               , s = 50)
ax.legend(targets)
ax.grid()

# 3차원
from mpl_toolkits.mplot3d import Axes3D
pca = PCA(n_components=3)
principalComponents = pca.fit_transform(pca_df)
principalDf = pd.DataFrame(data = principalComponents
             , columns = ['principal component 1', 'principal component 2','principal component 3'])
finalDF = pd.concat([principalDF, df[input y column name]], axis=1)
# pca 그리기
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(1,1,1, projection="3d") 
ax.set_xlabel('Principal Component 1', fontsize = 15)
ax.set_ylabel('Principal Component 2', fontsize = 15)
ax.set_ylabel('Principal Component 3', fontsize = 15)
ax.set_title('3 component PCA', fontsize = 20)
targets = [0, 1] # y class에 맞춰서 변경
colors = ['r', 'g'] # targets 길이와 같이 color 입력
for target, color in zip(targets,colors):
    indicesToKeep = finalDf[y column name] == target
    ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']
               , finalDf.loc[indicesToKeep, 'principal component 2']
               , finalDf.loc[indicesToKeep, 'principal component 3']
               , c = color)
ax.legend(targets)
ax.grid()
posted by 초코렛과자
: