与系列、列表和独特元素混淆

Confusion with series, list and unique elements

我想寻求一些帮助,因为我无法理解 python 程序中的 TypeError。 这段代码:

users2 = np.random.choice(users,5000).tolist()
print len(users2)
print users2[0:20]

for user in users2:
   tags.append(user_counters["tags"].loc[user])

print type(tags)
print set(tags)

标签类型为列表。但是当我应用 set() 方法来获取 "tags" 列表的唯一元素时,出现以下错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

好的,我明白它的意思,但我不明白 "Series".

的类型是什么

另一方面,如果使用:

print tags.unique()

出现另一个错误:

AttributeError: 'list' object has no attribute 'unique'

注意:users_counters是dataframe的类型和users的类型list 及其来自 users_counters.

的元素

既然 tag 是列表 而 set() 是列表,为什么会出现 TypeError 错误?

提前致谢

您的 tagspandas.Series 个对象的列表。当您从数据框中基于 loc 的选择构建列表时:

for user in users2:
   tags.append(user_counters["tags"].loc[user])

您将获得 Series。然后你尝试从系列列表中创建一个集合,但你做不到,因为系列不可散列。

So why does TypeError mistake happen since tag is list and set() is for lists?

嗯? set 接受任何可迭代对象,并且该可迭代对象的元素用于构造结果 set。您的可迭代对象是 list,元素是 pandas.Series 对象。就是这个问题。

我怀疑您有一个由代表用户的一系列字符串索引的数据框...

>>> df = pd.DataFrame({'tag':[1,2,3, 4], 'c':[1.4,3.9, 2.8, 6.9]}, index=['ted','sara','anne', 'ted'])
>>> df
        c  tag
ted   1.4    1
sara  3.9    2
anne  2.8    3
ted   6.9    4
>>>

当您进行选择时,由于您的用户索引具有非唯一数据元素,因此当您进行以下选择时,您将得到 Series:

>>> df['tag'].loc['ted']
user
ted    1
ted    4
Name: a, dtype: int64
>>> type(df['a'].loc['ted'])
<class 'pandas.core.series.Series'>