Pandas为分组d中的每个组分配唯一的ID

2024-04-26 14:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有许多属性的数据帧。我想为这些属性的所有唯一组合指定一个id。在

假设这是我的测向:

df = pd.DataFrame(np.random.randint(1,3, size=(10, 3)), columns=list('ABC'))

   A  B  C
0  2  1  1
1  1  1  1
2  1  1  1
3  2  2  2
4  1  2  2
5  1  2  1
6  1  2  2
7  1  2  1
8  1  2  2
9  2  2  1

现在,我需要添加一个新列,并为惟一的组合添加一个id。它必须是0,如果组合只出现一次。在这种情况下:

^{pr2}$

我的第一种方法是使用for循环并检查每一行,如果在该行的值的dataframe中找到多个组合,则使用.query:

unique_combination = 1 #acts as a counter
df['unique_combination'] = 0    

for idx, row in df.iterrows():
    if len(df.query('A == @row.A & B == @row.B & C == @row.C')) > 1:
        # check, if one occurrence of the combination already has a value > 0???
        df.loc[idx, 'unique_combination'] = unique_combination
        unique_combination += 1

但是,我不知道如何检查是否已经为组合指定了ID(参见代码中的注释)。此外,我的方法感觉非常缓慢和粗糙(我有超过15000行)。你有没有看到一个不同的方法来解决我的问题?在

非常感谢!在


Tags: 数据方法iddataframedfforif属性
2条回答

Pandas版本0.20.2中添加的一个新功能会自动为您创建一列唯一的id。在

df['unique_id'] = df.groupby(['A', 'B', 'C']).ngroup()

给出以下输出

^{pr2}$

根据迭代的顺序给这些组指定id。在

请参阅此处的文档:https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#enumerate-groups

步骤1:使用值0指定新列

df['new'] = 0

步骤2:制作一个重复次数超过1的面具,即

^{pr2}$

步骤3:根据掩码指定因子分解值,即

df.loc[mask,'new'] = df.loc[mask,['A','B','C']].astype(str).sum(1).factorize()[0] + 1

# or
# df.loc[mask,'new'] = df.loc[mask,['A','B','C']].groupby(['A','B','C']).ngroup()+1 

输出:

   A  B  C  new
0  2  1  1    0
1  1  1  1    1
2  1  1  1    1
3  2  2  2    0
4  1  2  2    2
5  1  2  1    3
6  1  2  2    2
7  1  2  1    3
8  1  2  2    2
9  2  2  1    0

相关问题 更多 >