![](/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.