Python 数据透视表转换为defaultdict(列表)
我使用熊猫透视表。我需要将数据从透视表转换为defaultdict(列表) 这是我的dict透视表数据(Python 数据透视表转换为defaultdict(列表),python,pandas,defaultdict,Python,Pandas,Defaultdict,我使用熊猫透视表。我需要将数据从透视表转换为defaultdict(列表) 这是我的dict透视表数据(df.to_dict()): 我需要将上面的数据传输到下面: { 'formation1': [{ 'position1': { 'total_count': 2.0 'count_with_contract': 1.0 'percent': 0.0
df.to_dict()
):
我需要将上面的数据传输到下面:
{
'formation1': [{
'position1': {
'total_count': 2.0
'count_with_contract': 1.0
'percent': 0.0
} {
'position2': {
'total_count': 1.0
'count_with_contract': 0.0
'percent': 0.0
}
]
}
}
如何操作?首先筛选需要的列名称,然后在dict comprehension中创建嵌套字典:
df1 = df[['total_count','count_with_contract','percent']]
d = {i:[g.reset_index(level=0, drop=True).to_dict('index')] for i,g in df1.groupby(level=0)}
print (d)
{'formation1':[{'position1': {'total_count': 2, 'count_with_contract': 1, 'percent': 0.5},
'position2': {'total_count': 1, 'count_with_contract': 0, 'percent': 0.0}}]}
使用defaultdict
的解决方案(输出有点不同):
从集合导入defaultdict
df1=df['总计数','合同计数','百分比']
打印(df1)
d=默认DICT(列表)
对于(f,pos),df1.T.items()中的x:
d[f].追加({pos:x.to_dict()})
印刷品(d)
defaultdict(,
{'formation1':[{'position1':{'total_count':2.0,'count_with_contract':1.0,'percent':0.5}},
{'position2':{'total_count':1.0,'count_with_contract':0.0,'percent':0.0}]})
df1 = df[['total_count','count_with_contract','percent']]
d = {i:[g.reset_index(level=0, drop=True).to_dict('index')] for i,g in df1.groupby(level=0)}
print (d)
{'formation1':[{'position1': {'total_count': 2, 'count_with_contract': 1, 'percent': 0.5},
'position2': {'total_count': 1, 'count_with_contract': 0, 'percent': 0.0}}]}
from collections import defaultdict
df1 = df[['total_count','count_with_contract','percent']]
print (df1)
d = defaultdict(list)
for (f, pos), x in df1.T.items():
d[f].append({pos: x.to_dict()})
print (d)
defaultdict(<class 'list'>,
{'formation1': [{'position1': {'total_count': 2.0, 'count_with_contract': 1.0, 'percent': 0.5}},
{'position2': {'total_count': 1.0, 'count_with_contract': 0.0, 'percent': 0.0}}]})