30 essential Python packages for data engineering

PHPz
Release: 2023-04-12 16:58:07
forward
1745 people have browsed it

Python can be said to be the easiest programming language to get started. With the help of basic packages such as numpy and scipy, Python can be said to be the best language currently for data processing and machine learning. Thanks to all the experts and enthusiastic Python has a large community of contributors supporting technology development, with two various Python packages developed to aid data scientists in their work.

30 essential Python packages for data engineering

In this article, we will introduce some very unique and easy-to-use Python packages that can help you build data workflows in many ways.

1. Knockknock

Knockknock is a simple Python package that notifies you when a machine learning model training ends or crashes. We can get notifications through multiple channels, such as email, Slack, Microsoft Teams, etc.

In order to install this package, we use the following code.

pip install knockknock
Copy after login

For example, we can use the following code to notify the machine learning modeling training status to a specified email address.

from knockknock import email_senderfrom sklearn.linear_model import LinearRegressionimport numpy as np@email_sender(recipient_emails=["<your_email@address.com>", "<your_second_email@address.com>"], sender_email="<sender_email@gmail.com>")def train_linear_model(your_nicest_parameters):x = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])y = np.dot(x, np.array([1, 2])) + 3 regression = LinearRegression().fit(x, y)return regression.score(x, y)
Copy after login

This way you can get notified when a problem occurs or the function completes.

2. tqdm

When you need to iterate or loop, if you need to display a progress bar? Then tqdm is what you need. This package will provide a simple progress meter in your notebook or command prompt.

Let’s start with the installation package.

pip install tqdm
Copy after login

The following code can then be used to display the progress bar during the loop.

from tqdm import tqdmq = 0for i in tqdm(range(10000000)):q = i +1
Copy after login

30 essential Python packages for data engineering

Like the gifg above, it can display a nice progress bar on the notebook. It's useful when you have a complex iteration and want to track progress.

3. Pandas-log

Panda -log can provide feedback on basic operations of Panda, such as .query, .drop, .merge, etc. It is based on R's Tidyverse and can be used to understand all data analysis steps.

Install the package

pip install pandas-log
Copy after login

After installing the package, take a look at the example below.

import pandas as pdimport numpy as npimport pandas_logdf = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],"toy": [np.nan, 'Batmobile', 'Bullwhip'],"born": [pd.NaT, pd.Timestamp("1940-04-25"), pd.NaT]})
Copy after login

Then let us try to use the following code to make a simple pandas operation record.

with pandas_log.enable():res = (df.drop("born", axis = 1).groupby('name'))
Copy after login

30 essential Python packages for data engineering

Through pandas-log, we can obtain all execution information.

4. Emoji

As the name suggests, Emoji is a Python package that supports emoji text parsing. Usually, it is difficult for us to handle emojis in Python, but the Emoji package can help us with the conversion.

Use the following code to install the Emoji package.

pip install emoji
Copy after login

Look at the following code:

import emojiprint(emoji.emojize('Python is :thumbs_up:'))
Copy after login

30 essential Python packages for data engineering

With this package, you can easily output emoticons.

5, TheFuzz

TheFuzz uses Levenshtein distance to match text to calculate similarity.

pip install thefuzz
Copy after login

The following code describes how to use TheFuzz for similarity text matching.

from thefuzz import fuzz, process#Testing the score between two sentencesfuzz.ratio("Test the word", "test the Word!")
Copy after login

30 essential Python packages for data engineering

TheFuzz can also extract similarity scores from multiple words simultaneously.

choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"]process.extract("new york jets", choices, limit=2)
Copy after login

30 essential Python packages for data engineering

TheFuzz is suitable for any text data similarity detection, this work is very important in nlp.

6. Numerizer

Numerizer can convert the written numeric text into the corresponding integer or floating point number.

pip install numerizer
Copy after login

Then let’s try a few inputs to convert.

from numerizer import numerizenumerize('forty two')
Copy after login

30 essential Python packages for data engineering

If you use another writing style, it will also work.

numerize('forty-two')
Copy after login

30 essential Python packages for data engineering

numerize('nine and three quarters')
Copy after login

30 essential Python packages for data engineering

If the input is not a numeric expression, it will be retained:

numerize('maybe around nine and three quarters')
Copy after login

30 essential Python packages for data engineering

7、PyAutoGUI

PyAutoGUI 可以自动控制鼠标和键盘。

pip install pyautogui
Copy after login

然后我们可以使用以下代码测试。

import pyautoguipyautogui.moveTo(10, 15)pyautogui.click()pyautogui.doubleClick()pyautogui.press('enter')
Copy after login

上面的代码会将鼠标移动到某个位置并单击鼠标。 当需要重复操作(例如下载文件或收集数据)时,非常有用。

8、Weightedcalcs

Weightedcalcs 用于统计计算。 用法从简单的统计数据(例如加权平均值、中位数和标准变化)到加权计数和分布等。

pip install weightedcalcs
Copy after login

使用可用数据计算加权分布。

import seaborn as snsdf = sns.load_dataset('mpg')import weightedcalcs as wccalc = wc.Calculator("mpg")
Copy after login

然后我们通过传递数据集并计算预期变量来进行加权计算。

calc.distribution(df, "origin")
Copy after login

30 essential Python packages for data engineering

9、scikit-posthocs

scikit-posthocs 是一个用于“事后”测试分析的 python 包,通常用于统计分析中的成对比较。 该软件包提供了简单的类似 scikit-learn API 来进行分析。

pip install scikit-posthocs
Copy after login

然后让我们从简单的数据集开始,进行 ANOVA 测试。

import statsmodels.api as saimport statsmodels.formula.api as sfaimport scikit_posthocs as spdf = sa.datasets.get_rdataset('iris').datadf.columns = df.columns.str.replace('.', '')lm = sfa.ols('SepalWidth ~ C(Species)', data=df).fit()anova = sa.stats.anova_lm(lm)print(anova)
Copy after login

30 essential Python packages for data engineering

获得了 ANOVA 测试结果,但不确定哪个变量类对结果的影响最大,可以使用以下代码进行原因的查看。

sp.posthoc_ttest(df, val_col='SepalWidth', group_col='Species', p_adjust='holm')
Copy after login

30 essential Python packages for data engineering

使用 scikit-posthoc,我们简化了事后测试的成对分析过程并获得了 P 值

10、Cerberus

Cerberus 是一个用于数据验证的轻量级 python 包。

pip install cerberus
Copy after login

Cerberus 的基本用法是验证类的结构。

from cerberus import Validatorschema = {'name': {'type': 'string'}, 'gender':{'type': 'string'}, 'age':{'type':'integer'}}v = Validator(schema)
Copy after login

定义好需要验证的结构后,可以对实例进行验证。

document = {'name': 'john doe', 'gender':'male', 'age': 15}v.validate(document)
Copy after login

30 essential Python packages for data engineering

如果匹配,则 Validator 类将输出True 。 这样我们可以确保数据结构是正确的。

11、ppscore

ppscore 用于计算与目标变量相关的变量的预测能力。 该包计算可以检测两个变量之间的线性或非线性关系的分数。 分数范围从 0(无预测能力)到 1(完美预测能力)。

pip install ppscore
Copy after login

使用 ppscore 包根据目标计算分数。

import seaborn as snsimport ppscore as ppsdf = sns.load_dataset('mpg')pps.predictors(df, 'mpg')
Copy after login

30 essential Python packages for data engineering

结果进行了排序。 排名越低变量对目标的预测能力越低。

12、Maya

Maya 用于尽可能轻松地解析 DateTime 数据。

pip install maya
Copy after login

然后我们可以使用以下代码轻松获得当前日期。

import mayanow = maya.now()print(now)
Copy after login

还可以为明天日期。

tomorrow = maya.when('tomorrow')tomorrow.datetime()
Copy after login

30 essential Python packages for data engineering

13、Pendulum

Pendulum 是另一个涉及 DateTime 数据的 python 包。 它用于简化任何 DateTime 分析过程。

pip install pendulum
Copy after login

我们可以对实践进行任何的操作。

import pendulumnow = pendulum.now("Europe/Berlin")now.in_timezone("Asia/Tokyo")now.to_iso8601_string()now.add(days=2)
Copy after login

30 essential Python packages for data engineering

14、category_encoders

category_encoders 是一个用于类别数据编码(转换为数值数据)的python包。 该包是各种编码方法的集合,我们可以根据需要将其应用于各种分类数据。

pip install category_encoders
Copy after login

可以使用以下示例应用转换。

from category_encoders import BinaryEncoderimport pandas as pdenc = BinaryEncoder(cols=['origin']).fit(df)numeric_dataset = enc.transform(df)numeric_dataset.head()
Copy after login

30 essential Python packages for data engineering

15、scikit-multilearn

scikit-multilearn 可以用于特定于多类分类模型的机器学习模型。 该软件包提供 API 用于训练机器学习模型以预测具有两个以上类别目标的数据集。

pip install scikit-multilearn
Copy after login

利用样本数据集进行多标签KNN来训练分类器并度量性能指标。

from skmultilearn.dataset import load_datasetfrom skmultilearn.adapt import MLkNNimport sklearn.metrics as metricsX_train, y_train, feature_names, label_names = load_dataset('emotions', 'train')X_test, y_test, _, _ = load_dataset('emotions', 'test')classifier = MLkNN(k=3)prediction = classifier.fit(X_train, y_train).predict(X_test)metrics.hamming_loss(y_test, prediction)
Copy after login

30 essential Python packages for data engineering

16、Multiset

Multiset类似于内置的set函数,但该包允许相同的字符多次出现。

pip install multiset
Copy after login

可以使用下面的代码来使用 Multiset 函数。

from multiset import Multisetset1 = Multiset('aab')set1
Copy after login

30 essential Python packages for data engineering

17、Jazzit

Jazzit 可以在我们的代码出错或等待代码运行时播放音乐。

pip install jazzit
Copy after login

使用以下代码在错误情况下尝试示例音乐。

from jazzit import error_track@error_track("curb_your_enthusiasm.mp3", wait=5)def run():for num in reversed(range(10)):print(10/num)
Copy after login

这个包虽然没什么用,但是它的功能是不是很有趣,哈

18、handcalcs

handcalcs 用于简化notebook中的数学公式过程。 它将任何数学函数转换为其方程形式。

pip install handcalcs
Copy after login

使用以下代码来测试 handcalcs 包。 使用 %%render 魔术命令来渲染 Latex 。

import handcalcs.renderfrom math import sqrt
Copy after login
%%rendera = 4b = 6c = sqrt(3*a + b/7)
Copy after login

30 essential Python packages for data engineering

19、NeatText

NeatText 可简化文本清理和预处理过程。 它对任何 NLP 项目和文本机器学习项目数据都很有用。

pip install neattext
Copy after login

使用下面的代码,生成测试数据

import neattext as nt mytext = "This is the word sample but ,our WEBSITE is https://exaempleeele.com ✨."docx = nt.TextFrame(text=mytext)
Copy after login

TextFrame 用于启动 NeatText 类然后可以使用各种函数来查看和清理数据。

docx.describe()
Copy after login

30 essential Python packages for data engineering

使用 describe 函数,可以显示每个文本统计信息。进一步清理数据,可以使用以下代码。

docx.normalize()
Copy after login

30 essential Python packages for data engineering

20、Combo

Combo 是一个用于机器学习模型和分数组合的 python 包。 该软件包提供了一个工具箱,允许将各种机器学习模型训练成一个模型。 也就是可以对模型进行整合。

pip install combo
Copy after login

使用来自 scikit-learn 的乳腺癌数据集和来自 scikit-learn 的各种分类模型来创建机器学习组合。

from sklearn.tree import DecisionTreeClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.ensemble import GradientBoostingClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_breast_cancerfrom combo.models.classifier_stacking import Stackingfrom combo.utils.data import evaluate_print
Copy after login

接下来,看一下用于预测目标的单个分类器。

# Define data file and read X and yrandom_state = 42X, y = load_breast_cancer(return_X_y=True)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4,random_state=random_state)# initialize a group of clfsclassifiers = [DecisionTreeClassifier(random_state=random_state),LogisticRegression(random_state=random_state),KNeighborsClassifier(),RandomForestClassifier(random_state=random_state),GradientBoostingClassifier(random_state=random_state)]clf_names = ['DT', 'LR', 'KNN', 'RF', 'GBDT']for i, clf in enumerate(classifiers):clf.fit(X_train, y_train)y_test_predict = clf.predict(X_test)evaluate_print(clf_names[i] + ' | ', y_test, y_test_predict)print()
Copy after login

30 essential Python packages for data engineering

使用 Combo 包的 Stacking 模型。

clf = Stacking(classifiers, n_folds=4, shuffle_data=False,keep_original=True, use_proba=False,random_state=random_state)clf.fit(X_train, y_train)y_test_predict = clf.predict(X_test)evaluate_print('Stacking | ', y_test, y_test_predict)
Copy after login

30 essential Python packages for data engineering

21、PyAztro

你是否需要星座数据或只是对今天的运气感到好奇? 可以使用 PyAztro 来获得这些信息! 这个包有幸运数字、幸运标志、心情等等。 这是我们人工智能算命的基础数据,哈

pip install pyaztro
Copy after login

使用以下代码访问今天的星座信息。

import pyaztropyaztro.Aztro(sign='gemini').description
Copy after login

30 essential Python packages for data engineering

22、Faker

Faker 可用于简化生成合成数据。 许多开发人员使用这个包来创建测试的数据。

pip install Faker
Copy after login

要使用 Faker 包生成合成数据

from faker import Fakerfake = Faker()
Copy after login

生成名字

fake.name()
Copy after login

30 essential Python packages for data engineering

每次从 Faker 类获取 .name 属性时,Faker 都会随机生成数据。

23、Fairlearn

Fairlearn 用于评估和减轻机器学习模型中的不公平性。 该软件包提供了许多查看偏差所必需的 API。

pip install fairlearn
Copy after login

然后可以使用 Fairlearn 的数据集来查看模型中有多少偏差。

from fairlearn.metrics import MetricFrame, selection_ratefrom fairlearn.datasets import fetch_adultdata = fetch_adult(as_frame=True)X = data.datay_true = (data.target == '>50K') * 1sex = X['sex']selection_rates = MetricFrame(metrics=selection_rate,y_true=y_true,y_pred=y_true,sensitive_features=sex)fig = selection_rates.by_group.plot.bar(legend=False, rot=0,title='Fraction earning over $50,000')
Copy after login

30 essential Python packages for data engineering

Fairlearn API 有一个 selection_rate 函数,可以使用它来检测组模型预测之间的分数差异,以便我们可以看到结果的偏差。

24、tiobeindexpy

tiobeindexpy 用于获取 TIOBE 索引数据。 TIOBE 指数是一个编程排名数据,对于开发人员来说是非常重要的因为我们不想错过编程世界的下一件大事。

pip install tiobeindexpy
Copy after login

可以通过以下代码获得当月前 20 名的编程语言排名。

from tiobeindexpy import tiobeindexpy as tbdf = tb.top_20()
Copy after login

30 essential Python packages for data engineering

25、pytrends

pytrends 可以使用 Google API 获取关键字趋势数据。如果想要了解当前的网络趋势或与我们的关键字相关的趋势时,该软件包非常有用。这个需要访问google,所以你懂的。

pip install pytrends
Copy after login

假设我想知道与关键字“Present Gift”相关的当前趋势,

from pytrends.request import TrendReqimport pandas as pdpytrend = TrendReq()keywords = pytrend.suggestions(keyword='Present Gift')df = pd.DataFrame(keywords)df
Copy after login

30 essential Python packages for data engineering

该包将返回与关键字相关的前 5 个趋势。

26、visions

visions 是一个用于语义数据分析的 python 包。 该包可以检测数据类型并推断列的数据应该是什么。

pip install visions
Copy after login

可以使用以下代码检测数据中的列数据类型。 这里使用 seaborn 的 Titanic 数据集。

import seaborn as snsfrom visions.functional import detect_type, infer_typefrom visions.typesets import CompleteSetdf = sns.load_dataset('titanic')typeset = CompleteSet()converting everything to stringsprint(detect_type(df, typeset))
Copy after login

30 essential Python packages for data engineering

27、Schedule

Schedule 可以为任何代码创建作业调度功能

pip install schedule
Copy after login

例如,我们想10 秒工作一次:

import scheduleimport timedef job():print("I'm working...")schedule.every(10).seconds.do(job)while True:schedule.run_pending()time.sleep(1)
Copy after login

30 essential Python packages for data engineering

28、autocorrect

autocorrect 是一个用于文本拼写更正的 python 包,可应用于多种语言。 用法很简单,并且对数据清理过程非常有用。

pip install autocorrect
Copy after login

可以使用类似于以下代码进行自动更正。

from autocorrect import Spellerspell = Speller()spell("I'm not sleaspy and tehre is no place I'm giong to.")
Copy after login

30 essential Python packages for data engineering

29、funcy

funcy 包含用于日常数据分析使用的精美实用功能。 包中的功能太多了,我无法全部展示出来,有兴趣的请查看他的文档。

pip install funcy
Copy after login

这里只展示一个示例函数,用于从可迭代变量中选择一个偶数,如下面的代码所示。

from funcy import select, evenselect(even, {i for i in range (20)})
Copy after login

30 essential Python packages for data engineering

30、IceCream

IceCream 可以使调试过程更容易。该软件包在打印/记录过程中提供了更详细的输出。

pip install icecream
Copy after login

可以使用下面代码

from icecream import icdef some_function(i):i = 4 + (1 * 2)/ 10 return i + 35ic(some_function(121))
Copy after login

30 essential Python packages for data engineering

也可以用作函数检查器。

def foo():ic()if some_function(12):ic()else:ic()foo()
Copy after login

30 essential Python packages for data engineering

The level of detail printed is ideal for analysis.

Summary

In this article, we summarize 30 unique Python packages that are useful in data work. Most software packages are easy to use and simple and clear, but some may have more functions and require further reading of their documentation. If you are interested, please go to the pypi website to search and view the homepage and documentation of the package. I hope this article will be helpful to you.

The above is the detailed content of 30 essential Python packages for data engineering. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template