본문 바로가기
Study/혼자 공부하는 판다스

혼자 공부하는 판다스 - 외부파일 읽어오기

by Wanooky 2022. 4. 4.

이번에는 외부파일을 읽어오는 법을 알아보자.

 

먼저 csv 파일이다.

 

불러오는 방법은

pd.read_csv(파일경로) 

 

이 함수의 옵션에 대해 알아보면

header = 0 -> 기본 값으로서 0행을 열로 지정한다.

header = 1 -> 1행을 열로 지정한다.

header = None -> 행을 열로 지정하지 않는다

 

index_col 옵션은 데이터프레임의 행 인덱스가 되는 열을 지정한다.

index_col = False -> 인덱스를 지정하지 않는다

index_col = 'c0' -> c0 열을 인덱스 지정한다.

 

실제로 코드를 실행해보자.

 

import pandas as pd
file_path = '/content/drive/MyDrive/part2/read_csv_sample.csv'

df1 = pd.read_csv(file_path)
print(df1)

df2 = pd.read_csv(file_path, header = None)
print(df2)

df3 = pd.read_csv(file_path, index_col = None)
print(df3)

df4 = pd.read_csv(file_path, index_col = 'c0')
print(df4)

   c0  c1  c2  c3
0   0   1   4   7
1   1   2   5   8
2   2   3   6   9

    0   1   2   3
0  c0  c1  c2  c3
1   0   1   4   7
2   1   2   5   8
3   2   3   6   9

   c0  c1  c2  c3
0   0   1   4   7
1   1   2   5   8
2   2   3   6   9

    c1  c2  c3
c0            
0    1   4   7
1    2   5   8
2    3   6   9

 

옵션의 종류를 더 알아보자

path : 파일의 위치, URL

sep : 텍스트 데이터를 필드별로 구분하는 문자

header : 열 이름으로 사용될 행의 번호

index_col : 행 인덱스로 사용할 열의 번호 또는 열 이름

names : 열 이름으로 사용할 문자열의 리스트

skiprows : 처음 몇 줄을 skip할 것인지 설정, skip 하려는 행의 번호를 담은 리스트로 설정 가능

parse_dates : 날짜 텍스트를 datetime64로 변환할 것인지 설정 (기본값은 False)

skip_footer : 마지막 몇 줄을 skip할 것인지 설정

encoding : 텍스트 인코딩 종류를 지정

 

두번째는 excel 파일이다.

 

불러오는 방법은

pd.read_excel(파일 경로) 이다

csv 랑 비슷하게 header 옵션이 있다.

header=None으로 설정하면 자동으로 정수형 인덱스가 열 이름으로 할당 된다.

 

df1 = pd.read_excel('/content/drive/MyDrive/part2/남북한발전전력량.xlsx')
df2 = pd.read_excel('/content/drive/MyDrive/part2/남북한발전전력량.xlsx', header=None)

print(df1)
print(df2)

  전력량 (억㎾h) 발전 전력별  1990  1991  1992  1993  1994  1995  1996  1997  ...  2007  \
0        남한     합계  1077  1186  1310  1444  1650  1847  2055  2244  ...  4031   
1       NaN     수력    64    51    49    60    41    55    52    54  ...    50   
2       NaN     화력   484   573   696   803  1022  1122  1264  1420  ...  2551   
3       NaN    원자력   529   563   565   581   587   670   739   771  ...  1429   
4       NaN    신재생     -     -     -     -     -     -     -     -  ...     -   
5        북한     합계   277   263   247   221   231   230   213   193  ...   236   
6       NaN     수력   156   150   142   133   138   142   125   107  ...   133   
7       NaN     화력   121   113   105    88    93    88    88    86  ...   103   
8       NaN    원자력     -     -     -     -     -     -     -     -  ...     -   

   2008  2009  2010  2011  2012  2013  2014  2015  2016  
0  4224  4336  4747  4969  5096  5171  5220  5281  5404  
1    56    56    65    78    77    84    78    58    66  
2  2658  2802  3196  3343  3430  3581  3427  3402  3523  
3  1510  1478  1486  1547  1503  1388  1564  1648  1620  
4     -     -     -     -    86   118   151   173   195  
5   255   235   237   211   215   221   216   190   239  
6   141   125   134   132   135   139   130   100   128  
7   114   110   103    79    80    82    86    90   111  
8     -     -     -     -     -     -     -     -     -  

[9 rows x 29 columns]

          0       1     2     3     4     5     6     7     8     9   ...  \
0  전력량 (억㎾h)  발전 전력별  1990  1991  1992  1993  1994  1995  1996  1997  ...   
1         남한      합계  1077  1186  1310  1444  1650  1847  2055  2244  ...   
2        NaN      수력    64    51    49    60    41    55    52    54  ...   
3        NaN      화력   484   573   696   803  1022  1122  1264  1420  ...   
4        NaN     원자력   529   563   565   581   587   670   739   771  ...   
5        NaN     신재생     -     -     -     -     -     -     -     -  ...   
6         북한      합계   277   263   247   221   231   230   213   193  ...   
7        NaN      수력   156   150   142   133   138   142   125   107  ...   
8        NaN      화력   121   113   105    88    93    88    88    86  ...   
9        NaN     원자력     -     -     -     -     -     -     -     -  ...   

     19    20    21    22    23    24    25    26    27    28  
0  2007  2008  2009  2010  2011  2012  2013  2014  2015  2016  
1  4031  4224  4336  4747  4969  5096  5171  5220  5281  5404  
2    50    56    56    65    78    77    84    78    58    66  
3  2551  2658  2802  3196  3343  3430  3581  3427  3402  3523  
4  1429  1510  1478  1486  1547  1503  1388  1564  1648  1620  
5     -     -     -     -     -    86   118   151   173   195  
6   236   255   235   237   211   215   221   216   190   239  
7   133   141   125   134   132   135   139   130   100   128  
8   103   114   110   103    79    80    82    86    90   111  
9     -     -     -     -     -     -     -     -     -     -  

[10 rows x 29 columns]

 

세 번째는 json 파일이다. json은 데이터 공유를 목적으로 개발한 특수한 파일 형식이다.

아무튼 다음과 같다.

 

pd.read_json(파일 경로)

 

df = pd.read_json('/content/drive/MyDrive/part2/read_json_sample.json')
print(df)
print(df.index)

           name  year        developer opensource
pandas           2008    Wes Mckinneye       True
NumPy            2006  Travis Oliphant       True
matplotlib       2003   John D. Hunter       True
Index(['pandas', 'NumPy', 'matplotlib'], dtype='object')

 

web에서 가져오는 방법에 대해 알아보겠다

 

먼저 HTML 웹 페이지에서 표 속성을 가져오는 것을 알아보자.

 

pd.read_html(웹 주소 또는 html 파일 경로)

 

url = '/content/drive/MyDrive/part2/sample.html'

tables = pd.read_html(url)

print(len(tables))

for i in range(len(tables)):
  print('tables[%s]' %i)
  print(tables[i])

df = tables[1]

df.set_index(['name'], inplace=True)
print(df)

2


tables[0]
   Unnamed: 0  c0  c1  c2  c3
0           0   0   1   4   7
1           1   1   2   5   8
2           2   2   3   6   9


tables[1]
         name  year        developer  opensource
0       NumPy  2006  Travis Oliphant        True
1  matplotlib  2003   John D. Hunter        True
2      pandas  2008    Wes Mckinneye        True


            year        developer  opensource
name                                         
NumPy       2006  Travis Oliphant        True
matplotlib  2003   John D. Hunter        True
pandas      2008    Wes Mckinneye        True