我已经收到“ TypeError:'Series'对象是可变的,因此不能进行散列。”虽然我理解了它的含义,但似乎无法解决。由于元组是不可变的,因此我尝试将系列转换为元组(如下所示)。我收到相同的错误消息。您知道如何解决此问题吗?
import pandas as pd
data_file = pd.read_csv("file:///C:/Users/carte/OneDrive/Desktop/TEST.csv")
Jordan = []
Carter = []
Reece = []
Liam = []
Bryce = []
David = []
Jordan = data_file['Jordan']
Carter = data_file['Carter']
Reece = data_file['Reece']
Liam = data_file['Liam']
Bryce = data_file['Bryce']
David = data_file['David']
invite = []
invite.append(Carter)
invite.append(Jordan)
invite.append(Reece)
invite.append(David)
invite.append(Liam)
invite.append(Bryce)
tuple(invite)
invite = list(dict.fromkeys(invite))
print(invite)
在某些情况下,我的代码应该采用每个列表中的所有名称,并在最后打印单个列表之前删除重复项。
[诚如Makoto所言,问题不是invite
的类型,而是invite
的内容。看起来您正在尝试解压缩pandas.Series
的每个实例以填充列表,然后再使用dict.fromkeys()
进行重复数据删除。为此,您应该使用list.extend()
而不是list.append()
。前者扩展了一个列表,其中所有元素都包含在其参数中,而后者则将单个新元素添加到列表中[Difference between append vs. extend list methods in Python]。例如:
invite = []
invite.extend(Carter)
invite.extend(Jordan)
您可能还需要将pandas.Series
手动转换为列表,看起来像这样:
invite = []
invite.extend(Carter.to_list())
invite.extend(Jordan.to_list())
请注意,在从CSV提取数据之前无需创建空列表。
可能有很多不同的方法可以做到这一点,所以这是一个选择,它可以减少您需要的大量代码。
# Assuming 'invites' is a list of strings that needs to be reduced to uniques
# This method will maintain the order of your list, but remove duplicates
uniques = list({key:'' for key in invites}.keys())
# Using set() will remove duplicates but will not preserve the order of the entries
uniques = list(set(invites))