这篇文章主要介绍“有哪些数据工程必备的Python包”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“有哪些数据工程必备的Python包”文章能帮助大家解决问题。
@H_404_2@1、Knockknock
@H_404_2@Knockknock是一个简单的Python包,它会在机器学习模型训练结束或崩溃时通知您。我们可以通过多种渠道获得通知,如电子邮件、Slack、Microsoft Teams等。 @H_404_2@为了安装该包,我们使用以下代码。pip install knockknock@H_404_2@例如,我们可以使用以下代码将机器学习建模训练状态通知到指定的电子邮件地址。
from knockknock import email_senderfrom sklearn.linear_model import LinearRegressionimport numpy as np@email_sender(recipient_emails=["", ""], sender_email="")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)@H_404_2@这样就可以在该函数出现问题或者完成时获得通知。
2、tqdm
@H_404_2@当需要进行迭代或循环时,如果你需要显示进度条?那么tqdm就是你需要的。这个包将在你的笔记本或命令提示符中提供一个简单的进度计。 @H_404_2@让我们从安装包开始。pip install tqdm@H_404_2@然后可以使用以下代码来显示循环过程中的进度条。
from tqdm import tqdmq = 0for i in tqdm(range(10000000)):q = i +1@H_404_2@
3、Pandas-log
@H_404_2@Panda -log可以对Panda的基本操作提供反馈,如.query、.drop、.merge等。它基于R的Tidyverse,可以使用它了解所有数据分析步骤。 @H_404_2@安装包pip install pandas-log@H_404_2@安装包之后,看看下面的示例。
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]})@H_404_2@然后让我们尝试用下面的代码做一个简单的 pandas 操作记录。
with pandas_log.enable():res = (df.drop("born", axis = 1).groupby('name'))@H_404_2@
4、Emoji
@H_404_2@顾名思义,Emoji 是一个支持 emoji 文本解析的 Python 包。 通常,我们很难用 Python 处理表情符号,但 Emoji 包可以帮助我们进行转换。 @H_404_2@使用以下代码安装 Emoji 包。pip install emoji@H_404_2@看看下面代码:
import emojiprint(emoji.emojize('Python is :thumbs_up:'))@H_404_2@
5、TheFuzz
@H_404_2@TheFuzz 使用 Levenshtein 距离来匹配文本以计算相似度。pip install thefuzz@H_404_2@下面代码介绍如何使用 TheFuzz 进行相似性文本匹配。
from thefuzz import fuzz, process#Testing the score between two sentencesfuzz.ratio("Test the word", "test the Word!")@H_404_2@
choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"]process.extract("new york jets", choices, limit=2)@H_404_2@
6、Numerizer
@H_404_2@Numerizer 可将写入的数字文本转换为对应的整数或浮点数。pip install numerizer@H_404_2@然后 让我们尝试几个输入来进行转换。
from numerizer import numerizenumerize('forty two')@H_404_2@
numerize('forty-two')@H_404_2@
numerize('nine and three quarters')@H_404_2@
numerize('maybe around nine and three quarters')@H_404_2@
7、pyautogui
@H_404_2@pyautogui 可以自动控制鼠标和键盘。pip install pyautogui@H_404_2@然后我们可以使用以下代码测试。
import pyautoguipyautogui.moveto(10, 15)pyautogui.click()pyautogui.doubleClick()pyautogui.press('enter')@H_404_2@上面的代码会将鼠标移动到某个位置并单击鼠标。 当需要重复操作(例如下载文件或收集数据)时,非常有用。
8、Weightedcalcs
@H_404_2@Weightedcalcs 用于统计计算。 用法从简单的统计数据(例如加权平均值、中位数和标准变化)到加权计数和分布等。pip install weightedcalcs@H_404_2@使用可用数据计算加权分布。
import seaborn as snsdf = sns.load_dataset('mpg')import weightedcalcs as wccalc = wc.Calculator("mpg")@H_404_2@然后我们通过传递数据集并计算预期变量来进行加权计算。
calc.distribution(df, "origin")@H_404_2@
9、scikit-posthocs
@H_404_2@scikit-posthocs 是一个用于“事后”测试分析的 python 包,通常用于统计分析中的成对比较。 该软件包提供了简单的类似 scikit-learn API 来进行分析。pip install scikit-posthocs@H_404_2@然后让我们从简单的数据集开始,进行 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)@H_404_2@
sp.posthoc_ttest(df, val_col='SepalWidth', group_col='Species', p_adjust='holm')@H_404_2@
10、Cerberus
@H_404_2@Cerberus 是一个用于数据验证的轻量级 python 包。pip install cerberus@H_404_2@Cerberus 的基本用法是验证类的结构。
from cerberus import Validatorschema = {'name': {'type': 'string'}, 'gender':{'type': 'string'}, 'age':{'type':'integer'}}v = Validator(schema)@H_404_2@定义好需要验证的结构后,可以对实例进行验证。
document = {'name': 'john doe', 'gender':'male', 'age': 15}v.validate(document)@H_404_2@
11、ppscore
@H_404_2@ppscore 用于计算与目标变量相关的变量的预测能力。 该包计算可以检测两个变量之间的线性或非线性关系的分数。 分数范围从 0(无预测能力)到 1(完美预测能力)。pip install ppscore@H_404_2@使用 ppscore 包根据目标计算分数。
import seaborn as snsimport ppscore as ppsdf = sns.load_dataset('mpg')pps.predictors(df, 'mpg')@H_404_2@
12、Maya
@H_404_2@Maya 用于尽可能轻松地解析 DateTime 数据。pip install maya@H_404_2@然后我们可以使用以下代码轻松获得当前日期。
import mayaNow = maya.Now()print(Now)@H_404_2@还可以为明天日期。
tomorrow = maya.when('tomorrow')tomorrow.datetime()@H_404_2@
13、Pendulum
@H_404_2@Pendulum 是另一个涉及 DateTime 数据的 python 包。 它用于简化任何 DateTime 分析过程。pip install pendulum@H_404_2@我们可以对实践进行任何的操作。
import pendulumNow = pendulum.Now("Europe/Berlin")Now.in_timezone("Asia/Tokyo")Now.to_iso8601_string()Now.add(days=2)@H_404_2@
14、category_encoders
@H_404_2@category_encoders 是一个用于类别数据编码(转换为数值数据)的python包。 该包是各种编码方法的集合,我们可以根据需要将其应用于各种分类数据。pip install category_encoders@H_404_2@可以使用以下示例应用转换。
from category_encoders import BinaryEncoderimport pandas as pdenc = BinaryEncoder(cols=['origin']).fit(df)numeric_dataset = enc.transform(df)numeric_dataset.head()@H_404_2@
15、scikit-multilearn
@H_404_2@scikit-multilearn 可以用于特定于多类分类模型的机器学习模型。 该软件包提供 API 用于训练机器学习模型以预测具有两个以上类别目标的数据集。pip install scikit-multilearn@H_404_2@利用样本数据集进行多标签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)@H_404_2@
16、Multiset
@H_404_2@Multiset类似于内置的set函数,但该包允许相同的字符多次出现。pip install multiset@H_404_2@可以使用下面的代码来使用 Multiset 函数。
from multiset import Multisetset1 = Multiset('aab')set1@H_404_2@
17、Jazzit
@H_404_2@Jazzit 可以在我们的代码出错或等待代码运行时播放音乐。pip install jazzit@H_404_2@使用以下代码在错误情况下尝试示例音乐。
from jazzit import error_track@error_track("curb_your_enthusiasm.mp3", wait=5)def run():for num in reversed(range(10)):print(10/num)@H_404_2@这个包虽然没什么用,但是它的功能是不是很有趣,哈
18、handcalcs
@H_404_2@handcalcs 用于简化notebook中的数学公式过程。 它将任何数学函数转换为其方程形式。pip install handcalcs@H_404_2@使用以下代码来测试 handcalcs 包。 使用 %%render 魔术命令来渲染 Latex 。
import handcalcs.renderfrom math import sqrt
%%rendera = 4b = 6c = sqrt(3*a + b/7)@H_404_2@
19、NeatText
@H_404_2@NeatText 可简化文本清理和预处理过程。 它对任何 NLP 项目和文本机器学习项目数据都很有用。pip install neattext@H_404_2@使用下面的代码,生成测试数据
import neattext as nt mytext = "This is the word sample but ,our WEBSITE is https://exaempleeele.com ✨."docx = nt.TextFrame(text=mytext)@H_404_2@TextFrame 用于启动 NeatText 类然后可以使用各种函数来查看和清理数据。
docx.describe()@H_404_2@
docx.normalize()@H_404_2@
20、Combo
@H_404_2@Combo 是一个用于机器学习模型和分数组合的 python 包。 该软件包提供了一个工具箱,允许将各种机器学习模型训练成一个模型。 也就是可以对模型进行整合。pip install combo@H_404_2@使用来自 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@H_404_2@接下来,看一下用于预测目标的单个分类器。
# 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()@H_404_2@
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)@H_404_2@
21、PyAztro
@H_404_2@你是否需要星座数据或只是对今天的运气感到好奇? 可以使用 PyAztro 来获得这些信息! 这个包有幸运数字、幸运标志、心情等等。 这是我们人工智能算命的基础数据,哈pip install pyaztro@H_404_2@使用以下代码访问今天的星座信息。
import pyaztropyaztro.Aztro(sign='gemini').description@H_404_2@
22、Faker
@H_404_2@Faker 可用于简化生成合成数据。 许多开发人员使用这个包来创建测试的数据。pip install Faker@H_404_2@要使用 Faker 包生成合成数据
from faker import Fakerfake = Faker()@H_404_2@生成名字
fake.name()@H_404_2@
23、Fairlearn
@H_404_2@Fairlearn 用于评估和减轻机器学习模型中的不公平性。 该软件包提供了许多查看偏差所必需的 API。pip install fairlearn@H_404_2@然后可以使用 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')@H_404_2@
24、tiobeindexpy
@H_404_2@tiobeindexpy 用于获取 TIOBE 索引数据。 TIOBE 指数是一个编程排名数据,对于开发人员来说是非常重要的因为我们不想错过编程世界的下一件大事。pip install tiobeindexpy@H_404_2@可以通过以下代码获得当月前 20 名的编程语言排名。
from tiobeindexpy import tiobeindexpy as tbdf = tb.top_20()@H_404_2@
25、pytrends
@H_404_2@pytrends 可以使用 Google Api 获取关键字趋势数据。如果想要了解当前的网络趋势或与我们的关键字相关的趋势时,该软件包非常有用。这个需要访问google,所以你懂的。pip install pytrends@H_404_2@假设我想知道与关键字“Present Gift”相关的当前趋势,
from pytrends.request import TrendReqimport pandas as pdpytrend = TrendReq()keywords = pytrend.suggestions(keyword='Present Gift')df = pd.DataFrame(keywords)df@H_404_2@
26、visions
@H_404_2@visions 是一个用于语义数据分析的 python 包。 该包可以检测数据类型并推断列的数据应该是什么。pip install visions@H_404_2@可以使用以下代码检测数据中的列数据类型。 这里使用 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))@H_404_2@
@H_296_502@
27、Schedule
@H_404_2@Schedule 可以为任何代码创建作业调度功能pip install schedule@H_404_2@例如,我们想10 秒工作一次:
import scheduleimport timedef job():print("I'm working...")schedule.every(10).seconds.do(job)while True:schedule.run_pending()time.sleep(1)@H_404_2@
28、autocorrect
@H_404_2@autocorrect 是一个用于文本拼写更正的 python 包,可应用于多种语言。 用法很简单,并且对数据清理过程非常有用。pip install autocorrect@H_404_2@可以使用类似于以下代码进行自动更正。
from autocorrect import Spellerspell = Speller()spell("I'm not sleaspy and tehre is no place I'm giong to.")@H_404_2@
29、funcy
@H_404_2@funcy 包含用于日常数据分析使用的精美实用功能。 包中的功能太多了,我无法全部展示出来,有兴趣的请查看他的文档。pip install funcy@H_404_2@这里只展示一个示例函数,用于从可迭代变量中选择一个偶数,如下面的代码所示。
from funcy import select, evenselect(even, {i for i in range (20)})@H_404_2@
30、IceCream
@H_404_2@IceCream 可以使调试过程更容易。该软件包在打印/记录过程中提供了更详细的输出。pip install icecream@H_404_2@可以使用下面代码
from icecream import icdef some_function(i):i = 4 + (1 * 2)/ 10 return i + 35ic(some_function(121))@H_404_2@
def foo():ic()if some_function(12):ic()else:ic()foo()@H_404_2@
关于“有哪些数据工程必备的Python包”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程之家行业资讯频道,小编每天都会为大家更新不同的知识点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。