简体   繁体   中英

Using defaultdict to bin values in pandas

I am trying to use the following dictionary (' ContinentDict ') to bin countries by continent .

Thus, I would like to bin keys by value .

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'}

When I try option 1:

v = {}

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

I get the error:

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

When I try option 2:

from collections import defaultdict

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

I get the error:

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

Could anybody give me a helping hand?

For option 2, I think you missed .items() . This worked for me:

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)

Output:

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']})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM