![](/img/trans.png)
[英]Is there a way to create a dataframe from a dictionary with list of values?
[英]Create dataframe from list of dictionary values
我有一本字典,我想创建一个 dataframe ,其中列是每个键的所有单独值。 例如,如果字典看起来像这样:
d = {'gender': 'female',
'company': ['nike', 'adidas'],
'location': ['chicago', 'miami'],
'plan': 'high'}
我希望 dataframe 看起来像这样:
female nike adidas chicago miami high
1 1 1 1 1 1
你可以做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
这是一个天真的解决方案,但它有效。 这个想法是:
d
字典组织成一个计数器字典,例如{'female': 1,
'nike': 1,
'adidas': 1,
'chicago': 1,
'miami': 1,
'high': 1}
这是代码:
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.