我有数据帧:
df = pd.DataFrame([[1,'length',1],
[1,'diameter',40],
[2,'length',5],
[2,'diameter',100]], columns=['no.', 'property','value'])
或者:
no.0 property value
1 'length' 1
1 'diameter' 40
2 'length' 5
2 'diameter' 100
我正试图将它转换为这样的数据帧(第一列必须是索引(:
no.0 property
1 {'length': 1, 'diameter', 40}
2 {'length': 1, 'diameter', 40}
按no.
列分组,并在dict理解中创建记录
{k: {'property': dict(g.values)} for k,g in df.set_index('no.').groupby(level=0)}
{1: {'property': {'length': 1, 'diameter': 40}},
2: {'property': {'length': 5, 'diameter': 100}}}
如果您想要dataframe
格式的输出
df.set_index('no.').groupby(level=0)
.apply(lambda g: dict(g.values)).reset_index(name='property')
no. property
0 1 {'length': 1, 'diameter': 40}
1 2 {'length': 5, 'diameter': 100}
可以将set_index
到property
以及no.
上的groupby.agg
转换为dict
以获得内部dict
:
new_df = (
df.set_index('property')
.groupby('no.')
.agg(property=('value', lambda s: s.to_dict()))
)
new_df
:
property
no.
1 {'length': 1, 'diameter': 40}
2 {'length': 5, 'diameter': 100}
然后在DataFrame上to_dict
以获得最终输出
d = new_df.to_dict()
d
:
{1: {'property': {'length': 1, 'diameter': 40}},
2: {'property': {'length': 5, 'diameter': 100}}}
您可以透视数据帧,然后删除列级别,为每行创建字典,最后调用to_dict()
:
reshaped = df.pivot(['no.'],['property'],['value'])
reshaped.columns = reshaped.columns.droplevel()
reshaped.apply(lambda x: {'property': dict(x)}, axis=1).to_dict()
输出:
{1:
{'property':
{'diameter': 40,
'length': 1}},
2: {'property':
{'diameter': 100,
'length': 5}}
}