0

I have a dictionary and I want to create a dataframe where the columns are all the individual values from each key. For example, if the dictionary looks like this:

d = {'gender': 'female',
     'company': ['nike', 'adidas'],
     'location': ['chicago', 'miami'],
     'plan': 'high'}

I want the dataframe to look like this:

female  nike  adidas  chicago  miami  high
1       1     1       1        1      1
1
  • 1
    I think you need to explain this question a bit more. Commented Jun 26, 2020 at 23:08

2 Answers 2

1

You can do explode + value_counts

df=pd.Series(d).explode().value_counts().to_frame(0).T
   chicago  female  nike  miami  high  adidas
0        1       1     1      1     1       1
Sign up to request clarification or add additional context in comments.

2 Comments

I get the error "Series object has no attribute 'explode'". Can I not use explode when there is a list (like for 'company' and 'location')?
@hirshg update your panda to most current one , explode is after 0.25
0

Here's a naive solution but it works. The idea is that:

  1. organize that d dictionary into a counter dictionary such as
{'female': 1,
 'nike': 1,
 'adidas': 1,
 'chicago': 1,
 'miami': 1,
 'high': 1}
  1. and then from there, you can create a pandas df

Here's the code:

# 1. create list to count 
out = []
for value in d.values():
    if isinstance(value, list):
        out.extend(value)
    else:
        out.append(value)
# out = ['female', 'nike', 'adidas', 'chicago', 'miami', 'high']

# 2. count occurrence of each unique item in this out list
from collections import Counter
count = Counter(out)

# 3. pandas df from dictionary
import pandas as pd
pd.DataFrame([Counter(out)])

# output:
# female  nike  adidas  chicago  miami  high
# 1       1     1       1        1      1

1 Comment

The data comes like that from another source, so I can't just organize the dictionary like that, unfortunately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.