[Python]내가 필요할 때 뽑아쓰는 파이썬 코드모음
#다중라인그래프
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib import font_manager as fm
font_list = [font.name for font in fm.fontManager.ttflist]
font_list
plt.rc('font', family='Malgun Gothic')
plt.plot(df['연도'],df['지원자/고3'],df['연도'],df['지원자/고3'])
plt.ylabel('지원자/고3',fontsize=14)
plt.legend(['수도권','비수도권'], fontsize=14)
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.barh.html

pandas.DataFrame.plot.barh ¶ DataFrame.plot. barh ( x = None , y = None , ** kwargs ) [source] ¶ Make a horizontal bar plot. A horizontal bar plot is a plot that presents quantitative data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons...
pandas.pydata.org
plt.show()
#sns라인
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib import font_manager as fm
font_list = [font.name for font in fm.fontManager.ttflist]
font_list
plt.rc('font', family='Malgun Gothic')
import seaborn as sns
sns.lineplot(x='연도', y='지원자/고3', hue='시도', data=df)
plt.ylabel('지원자/고3',fontsize=14,color='white')
plt.xlabel('연도',fontsize=14,color='white')
plt.xticks(color='white', fontsize =15)
plt.yticks(color='white', fontsize =15)
#sns barplot
sns.barplot(
data= df2,
x= "지역",
y= "pro/inst"
)
plt.xticks( fontsize =10)
plt.yticks( fontsize =10)
plt.title('지역별 문화/예술자산 보유현황', color = "#000000", size = 25)
plt.show()
#df.info()
#값모두출력
pd.set_option('display.max_columns', 100) #pd 컬럼 결과 모두 출력
pd.set_option('display.max_rows', 500) #pd 행 결과 모두 출력
np.set_printoptions(threshold=np.inf) # 배열의 모두를 출력
#디렉토리 확인
!dir
!ls
#병합
df = pd.merge(df3,df,how = 'inner')
df = pd.concat([df2,df1],axis = 0)
#컬럼생성
df['지원자/고3'] = df['지원자 수']/df['3student_num']
#원하는 컬럼 뽑아오기
df = df[['year','country','3student_num']]
#컬럼이름바꾸기
df = df.rename(columns={'year':'연도','country':'시도'})
#컬럼에 있는 값 바꾸기
df.loc[(df.country=='서울')|(df.country=='경기')|(df.country=='인천'),'country'] = '수도권'
#파일
df.to_excel('high3student_num.xlsx')
df = pd.read_excel('연도별 고3학생수.xlsx')
#groupby.sum().reset_index()
df = df.groupby(['year','country']).sum().reset_index()
#전처리 과정
import numpy as np
import pandas as pd
import os
import glob
pd.set_option('display.max_columns', 100) #pd 컬럼 결과 모두 출력
pd.set_option('display.max_rows', 500) #pd 행 결과 모두 출력
np.set_printoptions(threshold=np.inf) # 배열의 모두를 출력
!dir
os.chdir('./Travel/')
os.getcwd
df = pd.read_excel('광역지자체 목적지 검색건수_2020.xlsx')
df.info()
df.isna().sum()
file_list = glob.glob('*')
df= pd.DataFrame()
for files in file_list[0:9]:
tmp= pd.read_excel(files,header=15,[15:])
df = pd.concat([df,tmp], ignore_index=True)

import pandas as pd import numpy as np from pandas import Series, DataFrame #. 배열 결합 (np.concatenate) np.concatenate? concatenate((a1, a2, ...), axis=0, out=None) ar1 = np.arange(4).reshape(2,2..
data-make.tistory.com
df = pd.merge(df3,df,how = 'inner')
df.dtypes.index[df.dtypes == 'int64']
#null값 존재하는 컬럼
null_columns = df.isna().sum().index[df.isna().sum() > 0 ]
null_columns
del_columns=['우편번호', '전화번호', '팩스번호', '홈페이지']
df.drop(del_columns,axis = 1,inplace=True)
numeric_columns = df.dtypes[df.dtypes == 'int64'].index #시리즈니까 .index 수치형 데이터
df[numeric_columns]
feature_columns = df.columns[pd.Series(df.columns).str.slice(-1) != '여'] #여 아닌 데이터들 불러모아ㅏ
feature_columns
#groupby
df.groupby(['연도','학제']).mean().입학정원
df.loc[df.학교명 == '서울대학교',:].groupby('연도').mean().입학정원
df_work = pd.read_excel(file_list[-1])
df_work = df_work[df_work.취업률 != '-']
df_work.취업률 = df_work.취업률.astype('float')
df_work['학과코드']
df_work[df_work.학과코드.isin(df_work.groupby('학과코드').mean().취업률.sort_values(ascending=False).head(100).index)]
#matplotlib 한글설정
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import rc
rc('font', family='Malgun Gothic')
%matplotlib inline
#sort_value ascending=False 내림차순
df_sort = df.sort_values('종합',ascending=False)
#평균값 컬럼 생성
df['종합'] = np.mean(df, axis=1)
#NaN 데이터 제거
df = df.dropna()
#데이터 채우기
df['A'].fillna('기존', inplace=True)
df['A'].fillna(0 , inplace=True)
#drop=True -> index 들어오지 않게 하기
df.reset_index(drop=True)
#간단한 정규화
df[‘A’] / df[‘A’].max()
#문서 한글 인코딩
encoding = ‘eur-kr’/’utf-8’/’cp949’
#pivot_table
df1 = df.pivot_table(
df, index= '장소', columns= '역명', aggfunc = [np.sum]
)
#Multicolunms 제거
df.columns = df.columns.droplevel([0,1])
#np.where
#변수의 특정값변경