【问题标题】:Adding to defaultdict keys using for loop使用 for 循环添加到 defaultdict 键
【发布时间】:2018-08-14 11:27:39
【问题描述】:

我尝试了在其他线程上找到的多种不同建议,但似乎没有任何效果(是的,我是编程新手,哈哈)。

我有以下代码:

SysLength = defaultdict(list) #empty dictionary 
for x in SystemDict: 
    length = len(SystemDict[x]) #obtains length of each system
    SysLength[x].append(length) #adds system and length to the dictionary
SysMin = sorted(SysLength, key=SysLength.get) #sorts systems from smallest to largest 

emailDict = defaultdict(list) #empty dictionary

for x in SysMin: #cycles through lowest system first 
    for email in SystemDicto3[x]: #cycles through email in the lowest system
        emailDict[email] = 0 #adds email to dictionary and sets it equal to 0 

for x in SysMin: 
    for email in SystemDicto3[x]: 
        if emailDict[email] < 3: #if count is below 3, pass email through
            emailDict[email] += 1 #adds 1 to each email passed through
            SystemDictu4[x].append(email)

我对这一行有疑问:

SystemDictu4[x].append(email)

我要做的是将“电子邮件”附加到键值“x”。 SystemDictu4 是一个默认字典,每个键下都有 1000 个条目,我需要将 email 变量添加到这些键中。

我收到以下错误:

TypeError: cannot concatenate a non-NDFrame object

【问题讨论】:

  • 看起来SystemDictu4[x] 是一个数据框,您正在尝试向其附加一个字符串。这永远行不通。
  • 我也是这么认为的,但是当我输入 type(SystemDictu4) 时,输出是 collections.defaultdict,当我尝试附加到它时,它会变成 df 吗?
  • type(SystemDictu4[x]) 怎么样?
  • 输入的输出是pandas.core.series.Series 为什么会变成这个?有没有办法按照我需要的方式追加?
  • 好吧,首先我要调查一下为什么您的字典中有一个pd.Series,而您却没想到它。你可以追加到一个系列,但我不确定这是你想要的。

标签: python pandas dictionary append key


【解决方案1】:

显示的代码是正确的,但正如@jpp 建议的那样,我查看了 SystemDictu4 字典的创建方式。我最初创建字典的方法是使用以下 sn-p 代码:

SystemDictu4 = defaultdict(list) #initializing dictionary
for item in SystemsList:
    SystemDictu4[item]=dfu4[dfu4[item]== 1.0]["Email"]

经过一些测试,我了解到将.values.tolist() 添加到最后一行的末尾(在 ['Email'] 之后),它可以工作并且不会更改为系列。谢谢大家的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2013-03-13
    • 2020-07-21
    • 2014-04-17
    相关资源
    最近更新 更多