從 Excel 工作表讀取資料

在 Python 中匯入與管理財務資料

Stefan Jansen

Instructor

從 Excel 匯入資料

excel.png

  • pd.read_excel(file, sheet_name=0)

    • 預設選取第一個工作表:sheet_name=0
    • 以名稱選取:sheet_name='amex'
    • 匯入多個工作表(清單):sheet_name=['amex', 'nasdaq']
在 Python 中匯入與管理財務資料

從單一工作表匯入

amex = pd.read_excel('listings.xlsx',   
                     sheet_name='amex',   
                     na_values='n/a')

amex.info()
RangeIndex: 360 entries, 0 to 359
Data columns (total 7 columns):
 #   Column                 Non-Null Count  Dtype  
 --  ------                 --------------  -----  
 0   Stock Symbol           360 non-null    object 
 1   Company Name           360 non-null    object 
 2   Last Sale              346 non-null    float64
 3   Market Capitalization  360 non-null    float64
 4   IPO Year               105 non-null    float64

在 Python 中匯入與管理財務資料

從兩個工作表匯入

listings = pd.read_excel('listings.xlsx',
                         sheet_name=['amex', 'nasdaq'],    # keys = sheet name    
                         na_values='n/a')                 # values = DataFrame 

listings['nasdaq'].info()
 #   Column                 Non-Null Count  Dtype  
 --  ------                 --------------  -----  
 0   Stock Symbol           3167 non-null   object 
 1   Company Name           3167 non-null   object 
 2   Last Sale              3165 non-null   float64
 3   Market Capitalization  3167 non-null   float64
 4   IPO Year               1386 non-null   float64
...
在 Python 中匯入與管理財務資料

取得工作表名稱

xls = pd.ExcelFile('listings.xlsx') # pd.ExcelFile object

exchanges = xls.sheet_names
exchanges
['amex', 'nasdaq', 'nyse']
nyse = pd.read_excel(xls, 
                     sheet_name=exchanges[2],
                     na_values='n/a')
在 Python 中匯入與管理財務資料

取得工作表名稱

nyse.info()
RangeIndex: 3147 entries, 0 to 3146
Data columns (total 7 columns):
 #   Column                 Non-Null Count  Dtype  
  --  ------                 --------------  -----  
 0   Stock Symbol           3147 non-null   object 
  1   Company Name           3147 non-null   object
 ...                        ... 
 6   Industry               2177 non-null   object 
dtypes: float64(3), object(4)
memory usage: 172.2+ KB
在 Python 中匯入與管理財務資料

一起來練習吧!

在 Python 中匯入與管理財務資料

Preparing Video For Download...