Python:用了這個庫,就可以跟 Excel 說再見了
今天分享一個個比 Excel 更好用的 Python 工具,看完后,估計你要跟 Excel 說拜拜了。它就是 Mito
Mito
Mito 是 Python 中的電子表格庫。簡單易用,如果你能編輯 Excel 文件,你就能編寫代碼,這是因為,我們在表格中執(zhí)行的每個操作,Mito 將自動生成對應的 Python 代碼。可以跟重復枯燥的操作說再見了。
官方文檔[1]
安裝 Mito
安裝前確保 Python 的版本在 3.6 及以上。
pip install mitoinstaller
然后執(zhí)行:
python -m mitoinstaller install
等待命令執(zhí)行完成。
mitoinstaller 安裝程序會為經典的 Jupyter Notebook 和 JupyterLab 安裝 Mito。它將自動啟動 JupyterLab,你也手動啟動 Jupyter Notebook 來使用 Mitosheet。
Mito 讀取文件
Excel 對行數(shù)有限制。如果打開包含數(shù)百萬行的文件,該文件將打開,但在 Excel 中您不會看到超過 1,048,576 行。
相比之下,Python 可以處理數(shù)百萬行。唯一的限制是您的 PC 的計算能力。讓我們看看如何使用 Mito 讀取文件。
在讀取 CSV 文件之前,首先,我們需要創(chuàng)建一個 Mito 電子表格。為此,我們運行下面的代碼。
import mitosheet
mitosheet.sheet()
運行之后,就可以讀取 CSV 文件了,這里將使用一個包含學校成績的數(shù)據集[2],然后如下所示進行導入。
導入之后,將自動生成以下代碼:
import pandas as pd
StudentsPerformance_csv = pd.read_csv(r'StudentsPerformance.csv')
Mito 的自動化
用 Excel 的話,你只能完成基本操作的自動化,而 Mito 沒有限制。
使用 Mito,你可以做更多的事情,比如通過電子郵件發(fā)送報告,使用 WhatsApp 發(fā)送文件,使用 Google 表格作為基本數(shù)據庫等。
讓我們用 Mito 記錄一些動作,就好像我們在使用 Excel 一樣。
創(chuàng)建/重命名列
會自動生成如下代碼:
# Added column new-column-uca5 to StudentsPerformance_csv
StudentsPerformance_csv.insert(8, 'new-column-uca5', 0)
# Renamed new-column-uca5 to average in StudentsPerformance_csv
StudentsPerformance_csv.rename(columns={'new-column-uca5': 'average'}, inplace=True)
求和
會自動生成如下代碼:
# Set new-column-uca5 in StudentsPerformance_csv to =(math score+reading score+writing score)/3
StudentsPerformance_csv['average'] = (StudentsPerformance_csv['math score']+StudentsPerformance_csv['reading score']+StudentsPerformance_csv['writing score'])/3
創(chuàng)建數(shù)據透視表
會自動生成如下代碼:
# Imported StudentsPerformance.csv
import pandas as pd
StudentsPerformance_csv = pd.read_csv(r'StudentsPerformance.csv')
# Pivoted StudentsPerformance_csv into df2
unused_columns = StudentsPerformance_csv.columns.difference(set(['race/ethnicity']).union(set([])).union(set({'math score', 'reading score'})))
tmp_df = StudentsPerformance_csv.drop(unused_columns, axis=1)
pivot_table = tmp_df.pivot_table(
index=['race/ethnicity'],
values=['math score', 'reading score'],
aggfunc={'math score': ['mean'], 'reading score': ['mean']}
)
pivot_table.columns = [flatten_column_header(col) for col in pivot_table.columns.values]
df2 = pivot_table.reset_index()
創(chuàng)建一個柱狀圖
使用 Mito 可以輕松創(chuàng)建餅圖和條形圖等基本可視化。我們只需要點擊“圖表”并選擇圖表類型。
讓我們?yōu)橹皠?chuàng)建的數(shù)據透視表創(chuàng)建一個條形圖,在 X 軸上顯示“種族/民族”,在 Y 軸上顯示“數(shù)學分數(shù)平均值”:
不錯吧,a、b、c 和 d 中生成的代碼行相當于 Excel 宏。每次我們運行代碼時,Mito 都會執(zhí)行所有記錄的動作。
最后的話
如有所助,在看、關注支持。
官方文檔: https://docs.trymito.io/getting-started/installing-mito
[2]數(shù)據集: https://drive.google.com/file/d/1V9Hw_N73zsc56j8J9R8DrluSmi5yU3eg/view
