python - 基于2个元素的列表去重列表

标签 python pandas csv

我有一个列表列表,如下所示:

[[Joel,Green,597], [Katie,Higgins,623], [Joel,Green,123], ...]

我想通过查看名字和姓氏来删除列表中的元素(应删除具有相同名字和姓氏的元素)。在上面的例子中,结果列表应该只包含:

[[Katie,Higgins,623]]

我试过下面的代码,但只有当某些列表的所有三个元素都相同时,它才会执行重复删除:

newlist = []
reader = csv.reader(f,delimiter=",")  # read content
my_list = list(reader) #put content in my_list
for i in my_list:
    if i not in newlist:
        newlist.append(i)

有人可以帮忙吗?

最佳答案

使用DataFrame.drop_duplicates :

pd.read_csv(filename, header=None, names=['first','last','val']) \
  .drop_duplicates(['first','last'], keep=False) \
  .values.tolist()

来自文档:

keep : {‘first’, ‘last’, False}, default ‘first’

first : Drop duplicates except for the first occurrence.
last : Drop duplicates except for the last occurrence.
False : Drop all duplicates.

关于python - 基于2个元素的列表去重列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47781900/

相关文章:

python - 具有类型类型的 singledispatchmethod

python - Pandas 样式的默认 float 格式

python - 细化/骨骼化扭曲了我的形象

Python:将一个数据帧中的值添加到另一个数据帧(具有多个条件)

python - 将重复的行标签转换为 Pandas 中的列标题

Python cx_Oracle 更新

pandas - 如果[姓名]列中的姓氏相似,请填写另一列的缺失值

r - fread 不喜欢字段少于其他行的行

csv - 使用PigStorage加载数据,缺少最后一个字段

javascript - 来自 CSV 的 d3 可缩放 TreeMap