首页 > 解决方案 > 如何识别列表中的重复字符串?

问题描述

我正在从 csv 文件的 DataFrame 中导入具有 1280 个(所以我认为)唯一 ID 的列。

我曾计划将每个 ID 作为键放入字典中,并将“0”设置为值。然后将所有内容放入一个新的 DataFrame 中。

当从 DataFrame 中提取列作为列表时,我注意到该数字减少到 1189 而不是 1280。

我想,原始 DataFrame 中必须有重复项。这将是一个惊喜,因为 ID 应该是唯一的 ID。我可以走捷径,只使用新数据框的列表。但是,我必须弄清楚发生了什么并识别重复项(如果有的话)。

唯一的问题是,我无法识别任何重复项。我不知道问题可能是什么。

import pandas as pd
from itertools import cycle

DF0 = pd.read_csv("FILENAME.csv", sep='$', encoding='utf-8-sig')

l_o_0 = ['0']

l_DF0 = list(DF0['Short_ID'])
print('  len of origin object   '+str(len(DF0['Short_ID'])))
print('            l_DF0 is a   '+str(type(l_DF0)))
print('                of len   '+str(len(l_DF0))+'\n')

d_DF0 = dict(zip(DF0['Short_ID'], cycle(l_o_0)))
print('  len of origin object   '+str(len(DF0['Short_ID'])))
print('            d_DF0 is a   '+str(type(d_DF0)))
print('                of len   '+str(len(d_DF0))+'\n')

print('           difference:   '+(str(len(DF0['Short_ID'])-len(d_DF0)))+'\n')

s_DF0 = set(l_DF0)
print('            s_DF0 is a   '+str(type(s_DF0)))
print('             of length   '+str(len(s_DF0))+'\n')

red_l_DF0 = list(s_DF0)
print('        red_l_DF0 is a   '+str(type(red_l_DF0)))
print('             of length   '+str(len(red_l_DF0))+'\n')

l_prob = []
for item in l_DF0:
    if item not in red_l_DF0:
        l_prob.append(item)
print(len(l_prob))

输出是:

  len of origin object   1280
            l_DF0 is a   <class 'list'>
                of len   1280

  len of origin object   1280
            d_DF0 is a   <class 'dict'>
                of len   1189

           difference:   91

            s_DF0 is a   <class 'set'>
             of length   1189

        red_l_DF0 is a   <class 'list'>
             of length   1189

           l_prob is a   <class 'list'>
             of length   0
>>>

我根据在这里找到的内容尝试了上述操作:
Python 列表减法运算
要么我没有正确使用工具,要么是错误的工具。任何帮助将不胜感激 - 在此先感谢!

标签: pythonlistsubtraction

解决方案


使用熊猫的duplicated功能:

duplicated_stuff = DF0[DF0['Short_ID'].duplicated()]

根据您想看到的更改keep重复的参数。对于您的调试,您可能需要keep=False.


推荐阅读