各交易所的產業別公司數
「類別變數」是指依某種質性屬性,只能取有限個值的變數。「次數分配」則是呈現某個類別變數出現次數的方式。
回想前幾章的證券交易所資料。要了解像 'Technology'、'Finance' 這些 'Sector' 值的分佈,.mean() 並不實用,但 .value_counts() 和 .nunique() 就很有用。
在這個練習中,你要比較 AMEX、NASDAQ、NYSE 在各產業別的掛牌分佈。已經匯入 pandas 為 pd 與 matplotlib.pyplot 為 plt,而且先前練習的掛牌資訊已載入到字典 listings,其鍵為 'amex'、'nasdaq'、'nyse'。
本練習屬於課程
在 Python 中匯入與管理財務資料
練習說明
- 建立一個清單
exchanges,依上方順序放入各交易所名稱的字串,需與其字面相同。 - 使用 for 迴圈走訪
exchanges,迭代變數為含有各交易所名稱的exchange。在每次迭代中:- 對
'Sector'套用.value_counts(),並將結果指定給sectors。 - 將
sectors依降冪排序,並以長條圖繪製。 - 顯示結果。
- 對
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create the list exchanges
exchanges = [____, ____, ____]
# Iterate over exchanges then plot and show result
for ____ in exchanges:
sectors = listings[____].____.____()
# Sort in descending order and plot
sectors.sort_values(____=____).plot(____=____)
# Show the plot
plt.show()