如果你曾經(jīng)使用過(guò)Pandas處理表格數(shù)據(jù),你可能會(huì)熟悉導(dǎo)入數(shù)據(jù)、清洗和轉(zhuǎn)換的過(guò)程,然后將其用作模型的輸入。然而,當(dāng)你需要擴(kuò)展和將代碼投入生產(chǎn)時(shí),你的Pandas管道很可能開始崩潰并運(yùn)行緩慢。在這篇文章中,筆者將分享2個(gè)技巧,幫助你讓Pandas代碼快得離譜,提升數(shù)據(jù)處理效率并避免常見的陷阱。
在Pandas中,矢量化操作是一種強(qiáng)大的工具,它可以用一種更簡(jiǎn)潔和高效的方式處理整個(gè)數(shù)據(jù)框的列,而不是逐行循環(huán)。
廣播是矢量化操作的一個(gè)關(guān)鍵要素,它允許您直觀地操作具有不同形狀的對(duì)象。
eg1: 具有3個(gè)元素的數(shù)組a與標(biāo)量b相乘,得到與Source形狀相同的數(shù)組。
eg2: 在進(jìn)行加法運(yùn)算時(shí),將形狀為(4,1)的數(shù)組a與形狀為(3,)的數(shù)組b相加,結(jié)果會(huì)得到一個(gè)形狀為(4,3)的數(shù)組。
關(guān)于這一點(diǎn)已經(jīng)有很多文章,并且在深度學(xué)習(xí)中,大規(guī)模的矩陣乘法是非常常見的。在本文中,我們將利用兩個(gè)簡(jiǎn)短的例子上進(jìn)行討論。
首先,假設(shè)您想要計(jì)算給定整數(shù)在列中出現(xiàn)的次數(shù)。以下是 2 種可能的方法。
"""計(jì)算DataFrame X 中 "column_1" 列中等于目標(biāo)值 target 的元素個(gè)數(shù)。參數(shù):X: DataFrame,包含要計(jì)算的列 "column_1"。target: int,目標(biāo)值。返回值:int,等于目標(biāo)值 target 的元素個(gè)數(shù)。"""# 使用循環(huán)計(jì)數(shù)def count_loop(X, target: int) -> int: return sum(x == target for x in X["column_1"])# 使用矢量化操作計(jì)數(shù)def count_vectorized(X, target: int) -> int: return (X["column_1"] == target).sum()
現(xiàn)在假設(shè)有一個(gè)DataFrame帶有日期列并希望將其偏移給定的天數(shù)。使用矢量化操作計(jì)算如下:
def offset_loop(X, days: int) -> pd.DataFrame: d = pd.Timedelta(days=days) X["column_const"] = [x + d for x in X["column_10"]] return Xdef offset_vectorized(X, days: int) -> pd.DataFrame: X["column_const"] = X["column_10"] + pd.Timedelta(days=days) return X
第一個(gè)也是最直觀的迭代方法是使用Python for循環(huán)。
def loop(df: pd.DataFrame, remove_col: str, words_to_remove_col: str) -> list[str]: res = [] i_remove_col = df.columns.get_loc(remove_col) i_words_to_remove_col = df.columns.get_loc(words_to_remove_col) for i_row in range(df.shape[0]): res.append( remove_words( df.iat[i_row, i_remove_col], df.iat[i_row, i_words_to_remove_col] ) ) return result
def apply(df: pd.DataFrame, remove_col: str, words_to_remove_col: str) -> list[str]: return df.apply( func=lambda x: remove_words(x[remove_col], x[words_to_remove_col]), axis=1 ).tolist()
在 df.apply 的每次迭代中,提供的可調(diào)用函數(shù)獲取一個(gè) Series,其索引為 df.columns,其值是行的。這意味著 pandas 必須在每個(gè)循環(huán)中生成該序列,這是昂貴的。為了降低成本,最好對(duì)您知道將使用的 df 子集調(diào)用 apply,如下所示:
def apply_only_used_cols(df: pd.DataFrame, remove_col: str, words_to_remove_col: str) -> list[str]: return df[[remove_col, words_to_remove_col]].apply( func=lambda x: remove_words(x[remove_col], x[words_to_remove_col]), axis=1 )
使用itertuples與列表相結(jié)合進(jìn)行迭代肯定會(huì)更好。itertuples生成帶有行數(shù)據(jù)的(命名)元組。
def itertuples_only_used_cols(df: pd.DataFrame, remove_col: str, words_to_remove_col: str) -> list[str]: return [ remove_words(x[0], x[1]) for x in df[[remove_col, words_to_remove_col]].itertuples( index=False, name=None ) ]
zip接受可迭代對(duì)象并生成元組,其中第i個(gè)元組按順序包含所有給定可迭代對(duì)象的第i個(gè)元素。
def zip_only_used_cols(df: pd.DataFrame, remove_col: str, words_to_remove_col: str) -> list[str]: return [remove_words(x, y) for x, y in zip(df[remove_col], df[words_to_remove_col])]
def to_dict_only_used_columns(df: pd.DataFrame) -> list[str]: return [ remove_words(row[remove_col], row[words_to_remove_col]) for row in df[[remove_col, words_to_remove_col]].to_dict(orient="records") ]
除了我們討論的迭代技術(shù)之外,另外兩種方法可以幫助提高代碼的性能:緩存和并行化。如果使用相同的參數(shù)多次調(diào)用 pandas 函數(shù),緩存會(huì)特別有用。例如,如果remove_words應(yīng)用于具有許多重復(fù)值的數(shù)據(jù)集,您可以使用它functools.lru_cache來(lái)存儲(chǔ)函數(shù)的結(jié)果并避免每次都重新計(jì)算它們。要使用lru_cache,只需將@lru_cache裝飾器添加到 的聲明中remove_words,然后使用您首選的迭代方法將該函數(shù)應(yīng)用于您的數(shù)據(jù)集。這可以顯著提高代碼的速度和效率。以下面的代碼為例:
@lru_cachedef remove_words(...): ... # Same implementation as beforedef zip_only_used_cols_cached(df: pd.DataFrame, remove_col: str, words_to_remove_col: str) -> list[str]: return [remove_words(x, y) for x, y in zip(df[remove_col], df[words_to_remove_col])]
添加此裝飾器會(huì)生成一個(gè)函數(shù),該函數(shù)會(huì)“記住”之前遇到的輸入的輸出,從而無(wú)需再次運(yùn)行所有代碼。
最后一張王牌是使用 pandarallel 跨多個(gè)獨(dú)立的 df 塊并行化我們的函數(shù)調(diào)用。該工具易于使用:您只需導(dǎo)入并初始化它,然后將所有 .applys 更改為 .parallel_applys。
from pandarallel import pandarallelpandarallel.initialize(nb_workers=min(os.cpu_count(), 12))def parapply_only_used_cols(df: pd.DataFrame, remove_col: str, words_to_remove_col: str) -> list[str]: return df[[remove_col, words_to_remove_col]].parallel_apply( lambda x: remove_words(x[remove_col], x[words_to_remove_col]), axis=1 )
本文鏈接:http://www.www897cc.com/showinfo-26-64975-0.html讓你的Pandas代碼快得離譜的兩個(gè)技巧
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com
上一篇: 2024年不容錯(cuò)過(guò)的十大開發(fā)框架
下一篇: 12 月網(wǎng)約車行業(yè)共收到 8.94 億單環(huán)比上升 8.3%,如祺出行蟬聯(lián)訂單合規(guī)率榜首