【问题标题】:Pandas Drop Duplicates Series Hashing ErrorPandas Drop 重复序列哈希错误
【发布时间】:2019-02-02 10:15:27
【问题描述】:

我创建了一个 pandas 数据框,但是在删除重复行时出现错误:

TypeError: 'Series' 对象是可变的,因此它们不能被散列

这发生在我跑步时:

print(type(data)) # <class 'pandas.core.frame.DataFrame'> check that it's not a series
data.drop_duplicates(subset=['statement'], inplace=True)
print(data.info())

信息返回:

> class 'pandas.core.frame.DataFrame'
> Int64Index: 39671 entries, 0 to 39670
> Data columns (total 4 columns):
> statement          39671 non-null object
> topic_direction    39671 non-null object
> topic              39671 non-null object
> direction          39671 non-null object
> dtypes: object(4)
> memory usage: 1.5+ MB
> None

【问题讨论】:

  • 你的数据是什么样的。打印 info() 并显示 head()。
  • 看起来data['statement'] 是一系列系列。是吗? type(data['statement']) 报告什么?
  • @ScottBoston 我添加了信息
  • @DYZ type(data.statement) 返回
  • 系列不能用于重复消除,因为它是可变的。您必须将其转换为不可变的东西(frozensettuplestring?)

标签: python pandas


【解决方案1】:

'statement' 列中的各个元素是pandas.Series。这是一个明显的迹象,表明事情已经误入歧途。你可以通过运行data['statement'].apply(type) 来验证我的声明,你应该会看到一堆&lt;pandas.Series&gt; 或类似的东西。

如果您遇到这种情况,请尝试

df[~df['statement'].apply(tuple).duplicated()]

这会强制'statement' 列的每个元素成为tuple,它 可散列的。然后您可以找到重复的行并进行过滤。

【讨论】:

  • 看起来是这种情况,我找到了执行此操作的行。谢谢你,一旦时间到了,我会接受的。
  • 哇,@piRSquared。这是你以前遇到过的事情吗?伟大的洞察力。
  • 是的。但最大的线索是错误信息。 'Series' objects are mutable, thus they cannot be hashed。为了确定重复性,您必须能够散列。 Series 对象不像消息中所说的那样可散列。元组通常是运行相同逻辑的良好目标类。
猜你喜欢
  • 2015-03-19
  • 1970-01-01
  • 2022-01-05
  • 2012-04-15
  • 2013-07-03
  • 2014-10-17
  • 2016-11-21
  • 2019-07-06
  • 1970-01-01
相关资源
最近更新 更多