合併多個工作表的資料

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

Stefan Jansen

Instructor

合併 DataFrame

  • 串接或「堆疊」pd.DataFrame 清單
  • 語法:pd.concat([amex, nasdaq, nyse])

具有相同欄位的 NASDAQ、NYSE、AMEX 表

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

合併 DataFrame

  • 串接或「堆疊」pd.DataFrame 清單
  • 語法:pd.concat([amex, nasdaq, nyse])

tables with axis = 0

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

合併 DataFrame

  • 串接或「堆疊」pd.DataFrame 清單
  • 語法:pd.concat([amex, nasdaq, nyse])

三個表合併成一個長表

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

串接兩個 DataFrame

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

nyse = pd.read_excel('listings.xlsx', sheet_name='nyse', na_values=['n/a'])
pd.concat([amex, nyse]).info()
Int64Index: 3507 entries, 0 to 3146
Data columns (total 7 columns):
 #   Column                 Non-Null Count  Dtype  
 --  ------                 --------------  -----  
 0   Stock Symbol           3507 non-null   object 
...
在 Python 中匯入與管理財務資料

加入來源參考欄

amex['Exchange'] = 'AMEX' # Add column to reference source
nyse['Exchange'] = 'NYSE'

listings = pd.concat([amex, nyse])
listings.head(2)
  Stock Symbol    ...      Exchange       
0         XXII    ...         AMEX    
1          FAX    ...         AMEX
在 Python 中匯入與管理財務資料

合併三個 DataFrame

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

exchanges = xls.sheet_names
# Create empty list to collect DataFrames listings = []
for exchange in exchanges: listing = pd.read_excel(xls, sheet_name=exchange) # Add reference col listing['Exchange'] = exchange # Add DataFrame to list listings.append(listing)
# List of DataFrames combined_listings = pd.concat(listings)
在 Python 中匯入與管理財務資料

合併三個 DataFrame

combined_listings.info()
Int64Index: 6674 entries, 0 to 3146
Data columns (total 8 columns):
 #   Column                 Non-Null Count  Dtype  
 --  ------                 --------------  -----  
 0   Stock Symbol           6674 non-null   object 
 1   Company Name           6674 non-null   object 
 2   Last Sale              6590 non-null   float64
 3   Market Capitalization  6674 non-null   float64
 4   IPO Year               2852 non-null   float64
 5   Sector                 5182 non-null   object 
 6   Industry               5182 non-null   object 
 7   Exchange               6674 non-null   object 
dtypes: float64(3), object(5)
在 Python 中匯入與管理財務資料

一起來練習吧!

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

Preparing Video For Download...