从字典值列表创建dataframe

2024-04-25 13:10:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典,我想创建一个数据框,其中的列是每个键的所有单独值。例如,如果字典如下所示:

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

我希望数据帧如下所示:

female  nike  adidas  chicago  miami  high
1       1     1       1        1      1

Tags: 数据字典locationgendercompanyfemalehighplan
2条回答

这里有一个简单的解决方案,但它是有效的。其想法是:

  1. d字典组织到计数器字典中,如
{'female': 1,
 'nike': 1,
 'adidas': 1,
 'chicago': 1,
 'miami': 1,
 'high': 1}
  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

你可以做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

相关问题 更多 >