【问题标题】:how to drop duplicates in pandas when entries are sets设置条目时如何在熊猫中删除重复项
【发布时间】:2017-11-23 18:45:23
【问题描述】:

我有一个系列,其条目是集合。我想使用pandas.Series.drop_duplicates() 删除所有重复条目,但出现错误。这是一个例子:

import pandas as pd
ser = pd.Series([{1,2,3}, {4,5,6}, {4,5,6}])
ser.drop_duplicates()

最后一行给出了以下异常:

TypeError: unhashable type: 'set'

而我想得到:

0    {1, 2, 3}
1    {4, 5, 6}

这是一个错误吗?或者有其他方法可以实现吗?

【问题讨论】:

    标签: python-3.x pandas hash set series


    【解决方案1】:

    让我们使用astype(str) 然后duplicated

    ser[~ser.astype(str).duplicated(keep='first')]
    Out[170]: 
    0    {1, 2, 3}
    1    {4, 5, 6}
    dtype: object
    

    更多信息:

    ser.astype(str).duplicated(keep='first')
    Out[171]: 
    0    False
    1    False
    2     True
    dtype: bool
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2016-09-03
      • 2021-08-31
      • 2018-02-05
      • 1970-01-01
      • 2023-02-18
      • 2017-03-03
      • 2019-04-19
      • 1970-01-01
      相关资源
      最近更新 更多