import pandas as pd
import csv
url = 'https://ds-lecture-data.s3.ap-northeast-2.amazonaws.com/kt%26g/kt%26g_0.csv'
headers = ['분기', '매출액', '영업이익', '영업이익(발표기준)', '세전계속사업이익',
'당기순이익', '당기순이익(지배)', '당기순이익(비지배)', '자산총계', '부채총계',
'자본총계', '자본총계(지배)', '자본총계(비지배)', '자본금', '영업활동현금흐름',
'투자활동현금흐름', '재무활동현금흐름', '영업이익률', '순이익률', 'ROE(%)',
'ROA(%)', '부채비율', '자본유보율', 'EPS(원)', 'PER(배)']
- add a header in the csv file
#two ways to read csv file and add the header1. df=pd.read_csv(url, header = None)
df.columns = headers2. df= pd.read_csv(url, names = headers)
2. convert string to int
#string을 int로 바꾸고 영업이익률2 열에 추가하기 #영업이익률 = 영업이익/매출액*100#function to remove a comma in the string variablesdef toInt(string):
return int(string.replace(',',''))
df['영업이익'] = df['영업이익'].apply(toInt)
df['매출액'] = df['매출액'].apply(toInt)
df['영업이익률2'] = df['영업이익']/df['매출액']*100
- to make a column to be applied from the function, grab one column and put toInt in the apply. 하나하나 다 할 수가 없으니 열하나 잡고 어플라이로 함수를 다 적용시켜버림.
3. make a new DataFrame
#18/19년도 PDR 구하기 #PDR = 시가총액(기업가치)/시장규모*시장점유율 (시장규모 = 15조)1. way1 (column based)df2 = pd.DataFrame({'구분':['18년','19년'], '종가':[101500, 93800], "발행주식수":[137292497,137292497], "시가총액":[13935188445500,12878036218600], "시장점유율":[62.0,63.5]})
df2['PDR'] = df2['시가총액']/(15000000000000*df2['시장점유율']/100)*100
df2
df2['PDR']2. way2 (row based)columns=['구분', '종가','발행주식수','시가총액','시장점유율','PDR']
data= [['18년', 101500, 137292497, 13935188445500, 62, np.nan], ['19년', 93800, 137292497, 12878036218600, 63.5, np.nan]]
df2= pd.DataFrame(columns=columns, data=data)
4. convert string to integer ( X replace)
You can use astype() method to convert the data types to numeric.
df= df.astype({'매출액' : 'int'})
df['매출액'][0]
#str을 numeric으로 바꾸는 두 가지 방법(replace 제외)->얘네가 어떻게 쓰일 수 있는지 공부하기
#df['매출액'] = df['매출액'].astype(int)
#df['매출액']= pd.to_numeric(df['매출액'])
5. how to remove comma from string.
there are two ways
1. thousands method
When you read the csv file, command thousand at the first place, then you are not going to see any comma in your data)df= pd.read_csv(url, thousands=',')#thousand =","을 해서 불러왔을 때 이미 분기를 제외한 모든 것들이 int나 float으로 불러와진다.
2. df.column.str.replace(',','').astype('int64') mothodreplace the comma to the blank and make it to integer by using the astype()ex) removing comma and convert object to float together
df_tidy['lemon']= df_tidy['lemon'].replace(',','',regex=True).astype(float)
refernce: remove comma
6. convert every string data to float except the data in the first column.
#regex=True를 선언했을때 다른것에 붙은 콤마들이 다 사라짐df_new = df.columns[1:] #apply on every columns except the first one.
df[df_new] = df[df_new].replace(',','',regex=True).astype(float)
df.dtypes #여기까지하면 분기를 제외한 모든 변수들이 다 float으로 전환
df.fillna(0) #결측치 0으로 처리
df.describe()
regex=True를 하는게 정규 변환식에서 테이블 크기가 안맞는걸 맞춰주는것 같아보이는데.. 자세히 공부할 필요 있음.
- reference : Pandas trick
- https://nbviewer.jupyter.org/github/justmarkham/pandas-videos/blob/master/top_25_pandas_tricks.ipynb#7.-Convert-strings-to-numbers
*work to do : search about the re.sub