處理多個試算表
以人為閱讀對象(而非機器)設計的活頁簿,常會把同一主題的資料分散在多個工作表。例如,一家公司可能把各地區或各年度的交易分別放在不同的工作表中。
FreeCodeCamp 的 New Developer Survey 檔案採用類似做法:不同年度的回覆樣本各在不同工作表。你的任務是把它們彙整成同一個 dataframe 以便分析。
已將 pandas 以 pd 匯入。所有工作表都已讀入有序字典 responses,其中工作表名稱是鍵、dataframe 是值,因此你可以用 values() 方法取得各個 dataframe。
本練習屬於課程
使用 pandas 的精實資料導入
練習說明
- 建立一個空的 dataframe,命名為
all_responses。 - 設定一個
for迴圈,逐一走訪字典responses的值。 - 將每個 dataframe 串接到
all_responses,並把結果重新指定回同一個變數名稱。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create an empty dataframe
all_responses = ____
# Set up for loop to iterate through values in responses
for df in ____:
# Print the number of rows being added
print("Adding {} rows".format(df.shape[0]))
# Concatenate all_responses and df, assign result
all_responses = pd.concat(____)
# Graph employment statuses in sample
counts = all_responses.groupby("EmploymentStatus").EmploymentStatus.count()
counts.plot.barh()
plt.show()