Python 如何加快大熊猫数据帧的数据标记速度?

Python 如何加快大熊猫数据帧的数据标记速度?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个大熊猫数据框,大致如下所示 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

我有一个大熊猫数据框,大致如下所示

  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
我需要能够根据不同列中的分组对数据进行分类,例如,我的分类标准之一是,如果周期列中存在x和y周期,则使用标签标记标识列中的每个组

我必须对其进行分类的代码如下所示,生成最后一列:

for i in df['Identity'].unique():
    if (2 <= df[df['Identity']==i]['periods'].max() <= 5) :
        df.loc[df['Identity']==i,'label']='label 1'
df['Identity']中的i的
。唯一()

如果(2让我们尝试通过使用所有矢量化的操作来提高系统性能,而不是使用循环或
.apply()
函数,这也是通常在内部使用相对较慢的Python循环


使用
.groupby()
.transform()
在组内播放
max()
periods
以获得制作遮罩的系列。然后使用
.loc[]
带条件2的掩码的所有标签都基于组内周期的
最大值,如果不是,其他标签的逻辑是什么…其中两个标签基于组内周期的最大值,但我有另一个标签,它基于其中一个数据列中唯一值的数量。显示第一个例子是目前计算量最大的例子,因此我应该能够通过首先处理这个例子来获得最大收益!我的第二个标签目前看起来像:df[df['Identity']==I]['one'].round().unique()>5谢谢SeaBean!这太棒了,它工作得非常好。我用您的解决方案替换了两个标签标准。我不得不稍微修改最终的标签标准,并得出了m=df.round(0).groupby('Identity')['one'].transform('nunique'))结果是,一个运行时间为7分钟的代码块现在需要5秒,感谢您花了这么多时间提供帮助。
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