Python polars學(xué)習(xí)-08 分類數(shù)據(jù)處理

背景

polars學(xué)習(xí)系列文章倾芝,第8篇 分類數(shù)據(jù)處理(Categorical data)

該系列文章會分享到github,大家可以去下載jupyter文件,進(jìn)行參考學(xué)習(xí)
倉庫地址:https://github.com/DataShare-duo/polars_learn

小編運(yùn)行環(huán)境

import sys

print('python 版本:',sys.version.split('|')[0])
#python 版本: 3.11.9

import polars as pl

print("polars 版本:",pl.__version__)
#polars 版本: 0.20.22

分類數(shù)據(jù) Categorical data

分類數(shù)據(jù)就是平時在數(shù)據(jù)庫中能進(jìn)行編碼的數(shù)據(jù),比如:性別、年齡偏灿、國家、城市钝的、職業(yè) 等等翁垂,可以對這些數(shù)據(jù)進(jìn)行編碼,可以節(jié)省存儲空間

Polars 支持兩種不同的數(shù)據(jù)類型來處理分類數(shù)據(jù):EnumCategorical

  • 當(dāng)類別預(yù)先已知時使用 Enum扁藕,需要提前提供所有類別
  • 當(dāng)不知道類別或類別不固定時沮峡,可以使用 Categorical
enum_dtype = pl.Enum(["Polar", "Panda", "Brown"])
enum_series = pl.Series(
    ["Polar", "Panda", "Brown", "Brown", "Polar"], 
    dtype=enum_dtype)

cat_series = pl.Series(
    ["Polar", "Panda", "Brown", "Brown", "Polar"], 
    dtype=pl.Categorical
)

Categorical 類型

Categorical 相對比較靈活,不用提前獲取所有的類別亿柑,當(dāng)有新類別時邢疙,會自動進(jìn)行編碼

當(dāng)對來自2個不同的 Categorical 類別列直接進(jìn)行拼接時,以下這種方式會比較慢望薄,polars 是根據(jù)字符串出現(xiàn)的先后順序進(jìn)行編碼疟游,不同的字符串在不同的序列里面編碼可能不一樣,直接合并的話全局會再進(jìn)行一次編碼痕支,速度會比較慢:

cat_series = pl.Series(
    ["Polar", "Panda", "Brown", "Brown", "Polar"], dtype=pl.Categorical
)
cat2_series = pl.Series(
    ["Panda", "Brown", "Brown", "Polar", "Polar"], dtype=pl.Categorical
)

#CategoricalRemappingWarning: Local categoricals have different encodings, 
#expensive re-encoding is done to perform this merge operation. 
#Consider using a StringCache or an Enum type if the categories are known in advance
print(cat_series.append(cat2_series))

可以通過使用 polars 提供的全局字符緩存 StringCache颁虐,來提升數(shù)據(jù)處理效率

with pl.StringCache():
    cat_series = pl.Series(
        ["Polar", "Panda", "Brown", "Brown", "Polar"], dtype=pl.Categorical
    )
    cat2_series = pl.Series(
        ["Panda", "Brown", "Brown", "Polar", "Polar"], dtype=pl.Categorical
    )
    print(cat_series.append(cat2_series))

Enum

上面來自2個不同類型列進(jìn)行拼接的耗時的情況,在Enum中不會存在卧须,因?yàn)橐呀?jīng)提前獲取到了全部的類別

dtype = pl.Enum(["Polar", "Panda", "Brown"])
cat_series = pl.Series(["Polar", "Panda", "Brown", "Brown", "Polar"], dtype=dtype)
cat2_series = pl.Series(["Panda", "Brown", "Brown", "Polar", "Polar"], dtype=dtype)

print(cat_series.append(cat2_series))
#shape: (10,)
#Series: '' [enum]
[
    "Polar"
    "Panda"
    "Brown"
    "Brown"
    "Polar"
    "Panda"
    "Brown"
    "Brown"
    "Polar"
    "Polar"
]

如果有編碼的字符串類別另绩,當(dāng)不在提前獲取的Enum中時,則會報錯:OutOfBounds

dtype = pl.Enum(["Polar", "Panda", "Brown"])
try:
    cat_series = pl.Series(["Polar", "Panda", "Brown", "Black"], dtype=dtype)
except Exception as e:
    print(e)
#conversion from `str` to `enum` failed 
#in column '' for 1 out of 4 values: ["Black"]
#Ensure that all values in the input column are present 
#in the categories of the enum datatype.

比較

  • Categorical vs Categorical
  • Categorical vs String
  • Enum vs Enum
  • Enum vs String(該字符串必須要在提前獲取的Enum中)

Categorical vs Categorical

with pl.StringCache():
    cat_series = pl.Series(["Brown", "Panda", "Polar"], dtype=pl.Categorical)
    cat_series2 = pl.Series(["Polar", "Panda", "Black"], dtype=pl.Categorical)
    print(cat_series == cat_series2)
#shape: (3,)
#Series: '' [bool]
[
    false
    true
    false
]

Categorical vs String

cat_series = pl.Series(["Brown", "Panda", "Polar"], dtype=pl.Categorical)
print(cat_series <= "Cat")
#shape: (3,)
#Series: '' [bool]
[
    true
    false
    false
]

cat_series = pl.Series(["Brown", "Panda", "Polar"], dtype=pl.Categorical)
cat_series_utf = pl.Series(["Panda", "Panda", "A Polar"])
print(cat_series <= cat_series_utf)
#shape: (3,)
#Series: '' [bool]
[
    true
    true
    false
]

Enum vs Enum

dtype = pl.Enum(["Polar", "Panda", "Brown"])
cat_series = pl.Series(["Brown", "Panda", "Polar"], dtype=dtype)
cat_series2 = pl.Series(["Polar", "Panda", "Brown"], dtype=dtype)
print(cat_series == cat_series2)
#shape: (3,)
#Series: '' [bool]
[
    false
    true
    false
]

Enum vs String(該字符串必須要在提前獲取的Enum中)

try:
    cat_series = pl.Series(
        ["Low", "Medium", "High"], dtype=pl.Enum(["Low", "Medium", "High"])
    )
    cat_series <= "Excellent"
except Exception as e:
    print(e)
#conversion from `str` to `enum` failed 
#in column '' for 1 out of 1 values: ["Excellent"]
#Ensure that all values in the input column are present 
#in the categories of the enum datatype.

dtype = pl.Enum(["Low", "Medium", "High"])
cat_series = pl.Series(["Low", "Medium", "High"], dtype=dtype)
print(cat_series <= "Medium")
#shape: (3,)
#Series: '' [bool]
[
    true
    true
    false
]

dtype = pl.Enum(["Low", "Medium", "High"])
cat_series = pl.Series(["Low", "Medium", "High"], dtype=dtype)
cat_series2 = pl.Series(["High", "High", "Low"])
print(cat_series <= cat_series2)
#shape: (3,)
#Series: '' [bool]
[
    true
    true
    false
]

歷史相關(guān)文章


以上是自己實(shí)踐中遇到的一些問題花嘶,分享出來供大家參考學(xué)習(xí)笋籽,歡迎關(guān)注微信公眾號:DataShare ,不定期分享干貨

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末椭员,一起剝皮案震驚了整個濱河市车海,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌隘击,老刑警劉巖侍芝,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件研铆,死亡現(xiàn)場離奇詭異,居然都是意外死亡州叠,警方通過查閱死者的電腦和手機(jī)棵红,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來留量,“玉大人窄赋,你說我怎么就攤上這事哟冬÷ハǎ” “怎么了?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵浩峡,是天一觀的道長可岂。 經(jīng)常有香客問我,道長翰灾,這世上最難降的妖魔是什么缕粹? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮纸淮,結(jié)果婚禮上平斩,老公的妹妹穿的比我還像新娘。我一直安慰自己咽块,他們只是感情好绘面,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著侈沪,像睡著了一般揭璃。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上亭罪,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天瘦馍,我揣著相機(jī)與錄音,去河邊找鬼应役。 笑死情组,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的箩祥。 我是一名探鬼主播院崇,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼滥比!你這毒婦竟也來了亚脆?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤盲泛,失蹤者是張志新(化名)和其女友劉穎濒持,沒想到半個月后键耕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡柑营,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年屈雄,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片官套。...
    茶點(diǎn)故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡酒奶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出奶赔,到底是詐尸還是另有隱情惋嚎,我是刑警寧澤,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布站刑,位于F島的核電站另伍,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏绞旅。R本人自食惡果不足惜摆尝,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望因悲。 院中可真熱鬧堕汞,春花似錦、人聲如沸晃琳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蝎土。三九已至视哑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間誊涯,已是汗流浹背挡毅。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留暴构,地道東北人跪呈。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像取逾,于是被迫代替她去往敵國和親耗绿。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容