python - 在 for 循环中更新列表,它正在使用这个列表
问题描述
我正在处理一个内部包含一些值的数据框。问题是,我可能有重复。
我去了这个链接,但我找不到我需要的东西
我尝试的是创建一个重复列表,使用df.duplicated()
它为我提供每个索引True
的False
值。
然后对于此列表中结果所在的每个索引True
,我使用 df 从 df 获取 id df.loc[(df['id']== df['id'][dups]) ]
。根据这个结果,我调用一个函数 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
我想得到相同但没有不必要的重复
解决方案
如果您需要非重复 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
推荐阅读
- visual-studio - 将调试器附加到多个进程
- html - 嵌入 youtube 视频不适用于 vevo 等视频
- html - Dita-OT:标记为 HTML 转义字符串/字符(特别是括号)
- python - 将 xgboost 导入 Anaconda 时出现 Windows 错误 126
- highcharts - 基于下拉菜单更新 Highcharts 柱形图
- sql - 查询所有孩子都有一对/重复的父母
- python - 打印连续素数
- regex - 使用 Perl 内联编辑,如何在字符串第 N 次出现后插入一行?
- sql - 获取电子邮件线程的 SQL 结果
- vba - 单元格值更改时 VBA 发送电子邮件