您的位置:首页 >聚焦 >

世界速读:Python:用了这个库,就可以跟 Excel 说再见了

2022-07-13 22:36:19    来源:程序员客栈

今天分享一个个比 Excel 更好用的 Python 工具,看完后,估计你要跟 Excel 说拜拜了。它就是 Mito

Mito

Mito 是 Python 中的电子表格库。简单易用,如果你能编辑 Excel 文件,你就能编写代码,这是因为,我们在表格中执行的每个操作,Mito 将自动生成对应的 Python 代码。可以跟重复枯燥的操作说再见了。


(资料图)

官方文档[1]

安装 Mito

安装前确保 Python 的版本在 3.6 及以上。

pipinstallmitoinstaller

然后执行:

python-mmitoinstallerinstall

等待命令执行完成。

mitoinstaller 安装程序会为经典的 Jupyter Notebook 和 JupyterLab 安装 Mito。它将自动启动 JupyterLab,你也手动启动 Jupyter Notebook 来使用 Mitosheet。

Mito 读取文件

Excel 对行数有限制。如果打开包含数百万行的文件,该文件将打开,但在 Excel 中您不会看到超过 1,048,576 行。

相比之下,Python 可以处理数百万行。唯一的限制是您的 PC 的计算能力。让我们看看如何使用 Mito 读取文件。

在读取 CSV 文件之前,首先,我们需要创建一个 Mito 电子表格。为此,我们运行下面的代码。

importmitosheetmitosheet.sheet()

运行之后,就可以读取 CSV 文件了,这里将使用一个包含学校成绩的数据集[2],然后如下所示进行导入。

导入之后,将自动生成以下代码:

importpandasaspdStudentsPerformance_csv=pd.read_csv(r"StudentsPerformance.csv")

Mito 的自动化

用 Excel 的话,你只能完成基本操作的自动化,而 Mito 没有限制。

使用 Mito,你可以做更多的事情,比如通过电子邮件发送报告,使用 WhatsApp 发送文件,使用 Google 表格作为基本数据库等。

让我们用 Mito 记录一些动作,就好像我们在使用 Excel 一样。

创建/重命名列

会自动生成如下代码:

#Addedcolumnnew-column-uca5toStudentsPerformance_csvStudentsPerformance_csv.insert(8,"new-column-uca5",0)#Renamednew-column-uca5toaverageinStudentsPerformance_csvStudentsPerformance_csv.rename(columns={"new-column-uca5":"average"},inplace=True)

求和

会自动生成如下代码:

#Setnew-column-uca5inStudentsPerformance_csvto=(mathscore+readingscore+writingscore)/3StudentsPerformance_csv["average"]=(StudentsPerformance_csv["mathscore"]+StudentsPerformance_csv["readingscore"]+StudentsPerformance_csv["writingscore"])/3

创建数据透视表

会自动生成如下代码:

#ImportedStudentsPerformance.csvimportpandasaspdStudentsPerformance_csv=pd.read_csv(r"StudentsPerformance.csv")#PivotedStudentsPerformance_csvintodf2unused_columns=StudentsPerformance_csv.columns.difference(set(["race/ethnicity"]).union(set([])).union(set({"mathscore","readingscore"})))tmp_df=StudentsPerformance_csv.drop(unused_columns,axis=1)pivot_table=tmp_df.pivot_table(index=["race/ethnicity"],values=["mathscore","readingscore"],aggfunc={"mathscore":["mean"],"readingscore":["mean"]})pivot_table.columns=[flatten_column_header(col)forcolinpivot_table.columns.values]df2=pivot_table.reset_index()

创建一个柱状图

使用 Mito 可以轻松创建饼图和条形图等基本可视化。我们只需要点击“图表”并选择图表类型。

让我们为之前创建的数据透视表创建一个条形图,在 X 轴上显示“种族/民族”,在 Y 轴上显示“数学分数平均值”:

不错吧,a、b、c 和 d 中生成的代码行相当于 Excel 宏。每次我们运行代码时,Mito 都会执行所有记录的动作。

最后的话

如有所助,在看、关注支持。

参考资料[1]

官方文档: https://docs.trymito.io/getting-started/installing-mito

[2]

数据集: https://drive.google.com/file/d/1V9Hw_N73zsc56j8J9R8DrluSmi5yU3eg/view

关键词: 会自动生成 电子表格 电子邮件

相关阅读