新聞中心
今天就來介紹另外一個(gè)數(shù)據(jù)處理與分析工具,叫做??Polars??,它在數(shù)據(jù)處理的速度上更快,當(dāng)然里面還包括兩種API,一種是??Eager API??,另一種則是??Lazy API??,其中??Eager API??和??Pandas??的使用類似,語法類似差不太多,立即執(zhí)行就能產(chǎn)生結(jié)果。

而??Lazy API??和??Spark??很相似,會(huì)有并行以及對(duì)查詢邏輯優(yōu)化的操作。
模塊的安裝與導(dǎo)入
我們先來進(jìn)行模塊的安裝,使用??pip??命令
pip install polars
在安裝成功之后,我們分別用??Pandas??和??Polars??來讀取數(shù)據(jù),看一下各自性能上的差異,我們導(dǎo)入會(huì)要用到的模塊
import pandas as pd
import polars as pl
import matplotlib.pyplot as plt
%matplotlib inline
用??Pandas??讀取文件
本次使用的數(shù)據(jù)集是某網(wǎng)站注冊(cè)用戶的用戶名數(shù)據(jù),總共有360MB大小,我們先用??Pandas??模塊來讀取該??csv??文件
%%time
df = pd.read_csv("users.csv")
df.head()
output
可以看到用??Pandas??讀取??CSV??文件總共花費(fèi)了12秒的時(shí)間,數(shù)據(jù)集總共有兩列,一列是用戶名稱,以及用戶名稱重復(fù)的次數(shù)“n”,我們來對(duì)數(shù)據(jù)集進(jìn)行排序,調(diào)用的是??sort_values()??方法,代碼如下
%%time
df.sort_values("n", ascending=False).head()
output
用??Polars??來讀取操作文件
下面我們用??Polars??模塊來讀取并操作文件,看看所需要的多久的時(shí)間,代碼如下
%%time
data = pl.read_csv("users.csv")
data.head()
output
可以看到用??polars??模塊來讀取數(shù)據(jù)僅僅只花費(fèi)了730毫秒的時(shí)間,可以說是快了不少的,我們根據(jù)“n”這一列來對(duì)數(shù)據(jù)集進(jìn)行排序,代碼如下
%%time
data.sort(by="n", reverse=True).head()
output
對(duì)數(shù)據(jù)集進(jìn)行排序所消耗的時(shí)間為1.39秒,接下來我們用polars模塊來對(duì)數(shù)據(jù)集進(jìn)行一個(gè)初步的探索性分析,數(shù)據(jù)集總共有哪些列、列名都有哪些,我們還是以熟知“泰坦尼克號(hào)”數(shù)據(jù)集為例
df_titanic = pd.read_csv("titanic.csv")
df_titanic.columnsoutput
['PassengerId',
'Survived',
'Pclass',
'Name',
'Sex',
'Age',
......]
和??Pandas??一樣輸出列名調(diào)用的是??columns??方法,然后我們來看一下數(shù)據(jù)集總共是有幾行幾列的,
df_titanic.shape
output
(891, 12)
看一下數(shù)據(jù)集中每一列的數(shù)據(jù)類型
df_titanic.dtypes
output
[polars.datatypes.Int64,
polars.datatypes.Int64,
polars.datatypes.Int64,
polars.datatypes.Utf8,
polars.datatypes.Utf8,
polars.datatypes.Float64,
......]
填充空值與數(shù)據(jù)的統(tǒng)計(jì)分析
我們來看一下數(shù)據(jù)集當(dāng)中空值的分布情況,調(diào)用??null_count()??方法
df_titanic.null_count()
output
我們可以看到“Age”以及“Cabin”兩列存在著空值,我們可以嘗試用平均值來進(jìn)行填充,代碼如下
df_titanic["Age"] = df_titanic["Age"].fill_nan(df_titanic["Age"].mean())
計(jì)算某一列的平均值只需要調(diào)用??mean()??方法即可,那么中位數(shù)、最大/最小值的計(jì)算也是同樣的道理,代碼如下
print(f'Median Age: {df_titanic["Age"].median()}')
print(f'Average Age: {df_titanic["Age"].mean()}')
print(f'Maximum Age: {df_titanic["Age"].max()}')
print(f'Minimum Age: {df_titanic["Age"].min()}')output
Median Age: 29.69911764705882
Average Age: 29.699117647058817
Maximum Age: 80.0
Minimum Age: 0.42
數(shù)據(jù)的篩選與可視化
我們篩選出年齡大于40歲的乘客有哪些,代碼如下
df_titanic[df_titanic["Age"] > 40]
output
最后我們簡(jiǎn)單地來繪制一張圖表,代碼如下
fig, ax = plt.subplots(figsize=(10, 5))
ax.boxplot(df_titanic["Age"])
plt.xticks(rotation=90)
plt.xlabel('Age Column')
plt.ylabel('Age')
plt.show()
output
總體來說呢,??polars??在數(shù)據(jù)分析與處理上面和??Pandas??模塊有很多相似的地方,其中會(huì)有一部分的API存在著差異,感興趣的童鞋可以參考其官網(wǎng):https://www.pola.rs/
分享名稱:介紹一款進(jìn)階版的Pandas數(shù)據(jù)分析神器:Polars
URL鏈接:http://m.fisionsoft.com.cn/article/dhhdhhj.html


咨詢
建站咨詢
