正在更新for循环内的列表,该循环正在使用此lis

2024-09-29 17:15:39 发布

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

我正在处理一个包含一些值的数据帧。问题是,我可能有重复的。你知道吗

我继续做这个link但是我找不到我需要的东西

我尝试的是使用df.duplicated()创建一个重复的列表,它为每个索引提供TrueFalse值。
然后对于这个列表中的每个索引,结果是True,我使用df.loc[(df['id']== df['id'][dups]) ]从df获取id。根据这个结果,我调用一个函数giveID(),它返回要从重复列表中删除的索引列表。因为我不需要迭代应该被删除的重复项,所以在for循环期间是否可以从重复项列表中删除这些索引而不破坏所有内容?你知道吗

下面是我的df的一个例子(副本基于id列):

   | id | type
--------------
0  | 312| data2
1  | 334| data
2  | 22 | data1
3  | 312| data8
#Here 0 and 3 are duplicates based on ID

这是我代码的一部分:

duplicates = df.duplicated(subset='column_name',keep=False)
duplicates = duplicates[duplicates]


df_dup = df
listidx = []
i=0
for dups in duplicates.index:

    dup_id = df.loc[(df['id']== df['id'][dups])]
    for a in giveID(dup_id):
        if a not in listid:
            listidx.append(a)

#here i want to delete the all listidx from duplicates inside the for loop
#so that I don't iterate over unnecessary duplicates

def giveID(id)
#some code that returns a list of indexes

在我的代码中duplicates是这样的:

0          True
1          True
582        True
583        True
605        True
606        True
622        True
623        True
624        True
625        True
626        True
627        True
628        True
629        True
630        True
631        True
           ... 
1990368    True
1991030    True

我想得到相同的,但没有不必要的重复


Tags: 代码inidfalsetruedf列表for
1条回答
网友
1楼 · 发布于 2024-09-29 17:15:39

如果需要非重复ID的索引:

df = pd.DataFrame({'ID':[0,1,1,3], 'B':[0,1,2,3]})
   B  ID
0  0   0
1  1   1
2  2   1
3  3   3

# List of indexes
non_duplicated = df.drop_duplicates(subset='ID', keep=False).index

df.loc[df.index.isin(non_duplicated)]
   B  ID
0  0   0
3  3   3



相关问题 更多 >

    热门问题