![](/img/trans.png)
[英]How do I speed up applying a function to a large pandas dataframe?
[英]How can i speed up data labelling for a large pandas dataframe?
我有一個大的 pandas 數據框,大致看起來像這樣
Identity periods one two three Label
0 one 1 -0.462407 0.022811 -0.277357
1 one 1 -0.617588 1.667191 -0.370436
2 one 2 -0.604699 0.635473 -0.556088
3 one 2 -0.852943 1.087415 -0.784377
4 two 3 0.421453 2.390097 0.176333
5 two 3 -0.447321 -1.215280 -0.187156
6 two 4 0.398953 -0.334095 -1.194132
7 two 4 -0.324348 -0.842357 0.970825
我需要能夠根據各個列中的分組對數據進行分類,例如,我的分類標准之一是 label 標識列中的每個組,如果周期列中有 x 和 y 周期,則使用 label .
我必須對其進行分類的代碼如下所示,生成最后一列:
for i in df['Identity'].unique():
if (2 <= df[df['Identity']==i]['periods'].max() <= 5) :
df.loc[df['Identity']==i,'label']='label 1'
我也嘗試過使用的版本
df.groupby('Identity').apply().
但這並沒有更快。
我的數據目前大約有 280 萬行,大約有 900 個唯一身份。 代碼運行大約需要 5 分鍾,這對我來說表明循環中的代碼很慢,而不是循環使它變慢。
讓我們嘗試通過使用所有矢量化 Pandas 操作而不是使用循環或.apply()
function 來提高系統性能,這也只是通常使用相對較慢的 ZA7F5F35426B92741173Z 內部循環。
使用.groupby()
和.transform()
廣播組內periods
的max()
以獲得一系列用於制作掩碼。 然后將.loc[]
與條件 2 <= max <=5 的掩碼一起使用,並為滿足掩碼的此類行設置 label。
只要組內的最大周期在 2 <= max <=5 以內,就假定同一Identity
組的所有行的 label 相同。
m = df.groupby('Identity')['periods'].transform('max')
df.loc[(m >=2) & (m <=5), 'Label'] = 'label 1'
print(df)
Identity periods one two three Label
0 one 1 -0.462407 0.022811 -0.277357 label 1
1 one 1 -0.617588 1.667191 -0.370436 label 1
2 one 2 -0.604699 0.635473 -0.556088 label 1
3 one 2 -0.852943 1.087415 -0.784377 label 1
4 two 3 0.421453 2.390097 0.176333 label 1
5 two 3 -0.447321 -1.215280 -0.187156 label 1
6 two 4 0.398953 -0.334095 -1.194132 label 1
7 two 4 -0.324348 -0.842357 0.970825 label 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.