I'd like to create a closure table with pandas. Suppose you have hierarchical data, something like this with given ID's:
df = pd.DataFrame(
{
'unit_0': ['A','A','A','A','A','A','A','A'],
'unit_1': ['B','C','C','C','D','D','E','E'],
'unit_2': ['F','G','G','H','I','I','J','J']
}
)
units = [col for col in df]
closure = (df[units].melt(var_name='depth')
.drop_duplicates()
.rename(columns={'value': 'unit_name'}))
closure['unit_name_id'] = range(0, len(closure))
So now I would like to give the table parent_unit_id with something looking like this:
depth unit_name unit_name_id parent_unit_id
unit_0 A 0
unit_1 B 1 0
unit_1 C 2 0
unit_1 D 3 0
unit_1 E 4 0
unit_2 F 5 1
unit_2 G 6 2
unit_2 H 7 2
unit_2 I 8 3
unit_2 J 9 4
In this example every child only has one parent, but what if the frame looked like this instead (last J in unit_2 swaped to I):
df = pd.DataFrame(
{
'unit_0': ['A','A','A','A','A','A','A','A'],
'unit_1': ['B','C','C','C','D','D','E','E'],
'unit_2': ['F','G','G','H','I','I','J','I']
}
)
So that the parent_unit_id for I would be a list [3, 4]