使用 defaultdict 将 pandas 中的值装箱

Using defaultdict to bin values in pandas

我正在尝试使用以下字典('ContinentDict')按大陆 国家 分类。

因此,我想按值

ContinentDict  = {'China':'Asia', 
                  'United States':'North America', 
                  'Japan':'Asia', 
                  'United Kingdom':'Europe', 
                  'Russian Federation':'Europe', 
                  'Canada':'North America', 
                  'Germany':'Europe', 
                  'India':'Asia',
                  'France':'Europe', 
                  'South Korea':'Asia', 
                  'Italy':'Europe', 
                  'Spain':'Europe', 
                  'Iran':'Asia',
                  'Australia':'Australia', 
                  'Brazil':'South America'}

当我尝试 选项 1 时:

v = {}

for key, value in sorted(d.items()):
    v.setdefault(value, []).append(key)

我收到错误:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
TypeError:'dict' object is not callable

当我尝试 选项 2 时:

from collections import defaultdict

dictionary = defaultdict(list)
for key, value in ContinentDict:
dictionary[value].append(key)

我收到错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: first argument must be callable or None

有人可以帮帮我吗?

对于选项 2,我想你错过了 .items()。 这对我有用:

ContinentDict  = {'China':'Asia', 
                  'United States':'North America', 
                  'Japan':'Asia', 
                  'United Kingdom':'Europe', 
                  'Russian Federation':'Europe', 
                  'Canada':'North America', 
                  'Germany':'Europe', 
                  'India':'Asia',
                  'France':'Europe', 
                  'South Korea':'Asia', 
                  'Italy':'Europe', 
                  'Spain':'Europe', 
                  'Iran':'Asia',
                  'Australia':'Australia', 
                  'Brazil':'South America'}


dictionary = defaultdict(list)
for key, value in ContinentDict.items():
    dictionary[value].append(key)

print(dictionary)

输出:

defaultdict(<class 'list'>, {'Asia': ['China', 'Japan', 'India', 'South Korea', 'Iran'], 'North America': ['United States', 'Canada'], 'Europe': ['United Kingdom', 'Russian Federation', 'Germany', 'France', 'Italy', 'Spain'], 'Australia': ['Australia'], 'South America': ['Brazil']})