single positional indexer is out-of-bounds 오류

조회수 1157회

아래와 같이 코드를 작성 중입니다.

import OpenDartReader
import pandas as pd
import time

api_key = '01c9192342a2fd14777ac6df09ed6537937f7c7f' # OpenDart API 에서 받는 KEY 입력


stock_names = ['대창단조', '한국가구']
dart = OpenDartReader(api_key)

df2 = pd.DataFrame(columns=['유동자산', '부채총계', '자본총계', '매출액', '매출총이익', '영업이익',
                      '당기순이익', '영업활동현금흐름', '잉여현금흐름'], index=['1900-01-01'])


reprt_code = ['11013', '11012', '11014', '11011']

for stocks in stock_names:

    fileName = f'C:/Users/user/재무데이터/result_{str(stocks)}.xlsx'
    for i in range(2015, 2022):


        current_assets = [0, 0, 0, 0] # 유동자산
        liabilities = [0, 0, 0, 0] # 부채총계
        equity = [0, 0, 0, 0] # 자본총계
        revenue = [0, 0, 0, 0] # 매출액 
        grossProfit = [0, 0, 0, 0] # 매출총이익
        income = [0, 0, 0, 0] # 영업이익
        net_income = [0, 0, 0, 0] # 당기순이익
        cfo = [0, 0, 0, 0] # 영업활동현금흐름
        cfi = [0, 0, 0, 0] # 투자활동현금흐름
        fcf = [0, 0, 0, 0] # 잉여현금흐름 : 편의상 영업활동 - 투자활동 현금흐름으로 계산

        for j, k in enumerate(reprt_code):
            df1 = pd.DataFrame() # Raw Data
            if str(type(dart.finstate_all('004840', i, reprt_code=k, fs_div='CFS'))) == "<class 'NoneType'>":
                pass


            else: 
                df1 = df1.append(dart.finstate_all(stock_name, i, reprt_code=k, fs_div='CFS')) 

                condition = (df1.sj_nm == '재무상태표') & (df1.account_nm == '유동자산') # 유동자산
                condition_2 = (df1.sj_nm == '재무상태표') & (df1.account_nm == '부채총계') # 부채총계
                condition_3 = (df1.sj_nm == '재무상태표') & \
                            ((df1.account_nm == '자본총계') | (df1.account_nm == '반기말자본') | (df1.account_nm == '3분기말자본') | (df1.account_nm == '분기말자본') | (df1.account_nm == '1분기말자본'))  #자본총계
                # 손익계산서 부분
                condition_4 = ((df1.sj_nm == '손익계산서') | (df1.sj_nm == '포괄손익계산서')) & ((df1.account_nm == '매출액') | (df1.account_nm == '수익(매출액)'))
                condition_5 = ((df1.sj_nm == '손익계산서') | (df1.sj_nm == '포괄손익계산서')) & (df1.account_nm == '매출총이익')
                condition_6 = ((df1.sj_nm == '손익계산서') | (df1.sj_nm == '포괄손익계산서')) & \
                                ((df1.account_nm == '영업이익(손실)') | (df1.account_nm == '영업이익'))
                condition_7 = ((df1.sj_nm == '손익계산서') | (df1.sj_nm == '포괄손익계산서')) & \
                                ((df1.account_nm == '당기순이익(손실)') | (df1.account_nm == '당기순이익') | \
                                (df1.account_nm == '분기순이익') | (df1.account_nm == '분기순이익(손실)') | (df1.account_nm == '반기순이익') | (df1.account_nm == '반기순이익(손실)') | \
                                (df1.account_nm == '연결분기순이익') | (df1.account_nm == '연결반기순이익')| (df1.account_nm == '연결당기순이익')|(df1.account_nm == '연결분기(당기)순이익')|(df1.account_nm == '연결반기(당기)순이익')|\
                                (df1.account_nm == '연결분기순이익(손실)'))

                condition_8 = (df1.sj_nm == '현금흐름표') & ((df1.account_nm == '영업활동으로 인한 현금흐름') | (df1.account_nm == '영업활동 현금흐름'))
                condition_9 = (df1.sj_nm == '현금흐름표') & ((df1.account_nm == '투자활동으로 인한 현금흐름') | (df1.account_nm == '영업활동 현금흐름'))

                current_assets[j] = int(df1.loc[condition].iloc[0]['thstrm_amount'])
                liabilities[j] = int(df1.loc[condition_2].iloc[0]['thstrm_amount'])
                equity[j] = int(df1.loc[condition_3].iloc[0]['thstrm_amount'])
                revenue[j] = int(df1.loc[condition_4].iloc[0]['thstrm_amount'])
                grossProfit[j] = int(df1.loc[condition_5].iloc[0]['thstrm_amount'])
                income[j] = int(df1.loc[condition_6].iloc[0]['thstrm_amount'])
                net_income[j] = int(df1.loc[condition_7].iloc[0]['thstrm_amount'])
                cfo[j] = int(df1.loc[condition_8].iloc[0]['thstrm_amount'])
                cfi[j] = int(df1.loc[condition_9].iloc[0]['thstrm_amount'])
                fcf[j] = (cfo[j] - cfi[j])

                if k == '11013': # 1분기.
                    path_string = str(i) + '-03-31'
                elif k == '11012': # 2분기
                    path_string = str(i) + '-06-30'
                elif k == '11014': # 3분기
                    path_string = str(i) + '-09-30'
                else: 
                    path_string = str(i) + '-12-30'
                    revenue[j] = revenue[j] - (revenue[0] + revenue[1] + revenue[2])
                    grossProfit[j] = grossProfit[j] - (grossProfit[0] + grossProfit[1] + grossProfit[2])
                    income[j] = income[j] - (income[0] + income[1] + income[2])
                    net_income[j] = net_income[j] - (net_income[0] + net_income[1] + net_income[2])
                    fcf[j] = fcf[j] - (fcf[0] + fcf[1] + fcf[2])


                df2.loc[path_string] = [current_assets[j], liabilities[j], equity[j],
                                    revenue[j], grossProfit[j], income[j], net_income[j], cfo[j], fcf[j]]                
                df2.tail() 

            time.sleep(0.1)


    df2.drop(['1900-01-01'], inplace=True) # 첫 행 drop


    df2.to_excel(fileName) 


    df2 = pd.DataFrame(columns=['유동자산', '부채총계', '자본총계', '매출액', '매출총이익', '영업이익',
                            '당기순이익', '영업활동현금흐름', '잉여현금흐름'], index=['1900-01-01']) 

아래와 같이 오류가 발생 합니다. 어느문법이 어디가 문제인지 모르겠습니다.

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-92d266d82051> in <module>
     69                 income[j] = int(df1.loc[condition_6].iloc[0]['thstrm_amount'])
     70                 net_income[j] = int(df1.loc[condition_7].iloc[0]['thstrm_amount'])
---> 71                 cfo[j] = int(df1.loc[condition_8].iloc[0]['thstrm_amount'])
     72                 cfi[j] = int(df1.loc[condition_9].iloc[0]['thstrm_amount'])
     73                 fcf[j] = (cfo[j] - cfi[j])

~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
    893 
    894             maybe_callable = com.apply_if_callable(key, self.obj)
--> 895             return self._getitem_axis(maybe_callable, axis=axis)
    896 
    897     def _is_scalar_access(self, key: Tuple):

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1499 
   1500             # validate the location
-> 1501             self._validate_integer(key, axis)
   1502 
   1503             return self.obj._ixs(key, axis=axis)

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_integer(self, key, axis)
   1442         len_axis = len(self.obj._get_axis(axis))
   1443         if key >= len_axis or key < -len_axis:
-> 1444             raise IndexError("single positional indexer is out-of-bounds")
   1445 
   1446     # -------------------------------------------------------------------

IndexError: single positional indexer is out-of-bounds

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)