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

Python七号

共 2926字,需浏览 6分钟

 · 2022-07-13

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

Mito

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

官方文档[1]

安装 Mito

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

pip install mitoinstaller

然后执行:

python -m mitoinstaller install

等待命令执行完成。

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

Mito 读取文件

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

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

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

import mitosheet
mitosheet.sheet()

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

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

import pandas as pd
StudentsPerformance_csv = pd.read_csv(r'StudentsPerformance.csv')

Mito 的自动化

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

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

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

创建/重命名列


会自动生成如下代码:

# 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

创建数据透视表


会自动生成如下代码:

# 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()

创建一个柱状图

使用 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


浏览 20
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报