본문 바로가기

언어 꿀Tip/Python 꿀tip!

(67)
07_01_49. timeseries 그래프에 linear regression trend line 추가 import pandas as pd import numpy as np from matplotlib import pyplot as plt import matplotlib.pylab as plt2 import matplotlib.dates as mdates plt2.rcParams["figure.figsize"] = (8,2.5) fig, ax0 = plt.subplots() ax0.set_xlabel('year_month') ax0.tick_params(axis='x', labelrotation=45) ax0.set_ylabel('y') # ax0.set_ylim(400,1200) x = np.arange(df['date'].size) y = df['y'] fit = np.polyfit(x, y, 1 ) ..
07_01_48. DB2 연결하여 SQL로 데이터 산출 import ibm_db_dbi import pandas as pd conn = ibm_db_dbi.connect("DRIVER={IBM DB2 ODBC DRIVER}; Database=데이터베이스; Hostname=host_ip; Port=port_number; PROTOCOL=TCPIP; UID=USER_ID; PWD=USER_비밀번호", "", "") query = ''' 쿼리 입력 ''' # Sql df = pd.read_sql( query, conn)
07_01_47. json 파일 불러오기 두 개가 무슨 차이인지 모름! # 판매량 데이터 import json # method 1 with open('./data/etc/sample/data.json') as json_file: json_data = json.load(json_file) df = pd.DataFrame(json_data).drop(columns='index_col') # method 2 with open('./data/etc/data.json') as json_file: json_data = json.load(json_file) df = pd.DataFrame(list(json_data.values())[0])
07_01_46. 2x2 형태로 여러 line 중첩해서 그래프 그리기 2x2 형태 그래프 및 각 그래프에 여러 line 중첩해서 그리기 각 그래프 내에 범례 제거 각 그래프의 축 이름 (label) 제거 from matplotlib import pyplot as plt import matplotlib.pylab as plt2 import seaborn as sns # plot 크기 조정 plt2.rcParams["figure.figsize"] = (15,10) # 2x2 형태 생성 fig, axs = plt.subplots(2,2) # cd list에 속한 element에 따라 2x2 형태로 plot 그리기 l_cd = ['1','2','3','4'] # Flatten axx = axs.ravel() for i, v_cd in enumerate(l_cd): sns.line..
07_01_45. groupby 컬럼명 level 합치기 groupby 했을 때, qty에 대해서 합계, 평균, 분산 등 여러가지를 aggregate 하면, 컬럼명이 깔끔하지 않음! qty_sum, qty_mean과 같이 나타내기 위해서 아래 코드 이용! df_ag = df_1m_s.groupby(g_col, as_index=False).agg({"qty" : ["sum","mean","var","std","max","skew"]}).reset_index(drop=True) # 1 방법 df_ag.columns = ['_'.join(tup).rstrip('_') for tup in df_ag.columns.values] # 2 방법 df_ag.columns = list(map('_'.join, df_new_month.columns))
07_01_44. seaborn multiple line chart 여러개 동시에 그래프그리기 import seaborn as sns # df 내 months별 추이를 보고싶음 # cd별 month 에 따른 qty 추이 g = sns.lineplot(x="months", y="qty", hue="cd", data=df) g.legend(loc='upper right', bbox_to_anchor=(1.01,1)) # 범례 위치 지정
07_07_43. chi-square test (카이제곱 검정) import pandas as pd from scipy.stats import chisquare import scipy.stats as stats # df라는 데이터프레임에 x7_2, x5라는 변수가 존재한다고 했을 때! result_31=pd.crosstab(df.x7_2, df.x5) result_31_chi, p, dof, ex = stats.chi2_contingency(observed=result_31) # p : p-value chi-square test
07_01_41. 그래프 범례 삽입 (graph legend), 여러 line 겹쳐 그리기 여러개 plot이 존재할 때, 범례 추가하기 from matplotlib import pyplot as plt import matplotlib.pylab as plt2 plt2.rcParams["figure.figsize"] = (15,4) # plot 크기 조절 fig, ax0 = plt.subplots() ax0.set_xlabel('date') ax0.set_ylabel('amt') # 메인 축 label (축이름) ax0.set_ylim(1000000,2400000) # 메인 축 범위 조절 line0 = ax0.plot( df_tot['datecd'], df_tot['amt'], color='black' , label='tot') # 2중축 추가 ax1 = ax0.twinx() ax1.set_yl..
07_01_40. matplotlib plot 크기 조정 (plot size) %matplotlib inline import matplotlib.pylab as plt plt.rcParams["figure.figsize"] = (14,4) plt.rcParams['lines.linewidth'] = 2 plt.rcParams['lines.color'] = 'r' plt.rcParams['axes.grid'] = True 항목설명 "figure.figsize" 그림(figure)의 크기. (가로,세로) 인치 단위 'lines.linewidth' 선의 두께 'lines.color' 선의 색깔 'axes.grid' 차트내 격자선(grid) 표시 여부
07_01_39. matplotlib 그래프 이중축 graph 생성 및 축이름 import pandas as pd from matplotlib import pyplot as plt fig, ax0 = plt.subplots() ax1 = ax0.twinx() ax0.plot( df_tot['part_datecd'], df_tot['ntsal_amt_m'], color='black') ax1.plot( df_tot['part_datecd'], df_tot['ntsal_amt_ff_m'] , color='blue') ax0.set_xlabel('date') ax0.set_ylabel('amt') ax1.set_ylabel('amt(1')