Pandas DataFrame Groupby two columns and get different relation in same keys insert list
You could use pivot_table
and to_dict
:
(df.pivot_table(index='Head', columns='Relation', values='Tail', aggfunc=list)
.to_dict('index')
)
Or, the other way around:
(df.pivot_table(index='Relation', columns='Head', values='Tail', aggfunc=list)
.to_dict()
)
output:
{9: {0: [23, 12], 1: [0]}, 10: {0: [66, 61], 1: [11, 61]}}
post-processing the output to remove NaNs:
d = (df.pivot_table(columns='Head', index='Relation', values='Tail', aggfunc=list)
.to_dict()
)
d2 = {k: {k2:v2 for k2,v2 in v.items() if pd.isna(v2) is not True}
for k,v in d.items()}