Скажем, у меня есть следующий фрейм данных df
:
A B
0 mother1 NaN
1 NaN child1
2 NaN child2
3 mother2 NaN
4 NaN child1
5 mother3 NaN
6 NaN child1
7 NaN child2
8 NaN child3
Как вы могли бы превратить это в словарь, который дает:
results={'mother1':['child1','child2'],'mother2':['child1'],'mother3':['child1','child2','child3']}
Мой взгляд на это:
import pandas as pd
import numpy as np
results={}
for index1,row1 in df.iterrows():
if row1['A'] is not np.nan:
children=[]
for index2,row2 in df.iterrows():
if row2['B'] is not np.nan:
children.append(row2['B'])
results[row1['A']]=children
Однако результат неверен:
In[1]: results
Out[1]:
{'mother1': ['child1', 'child2', 'child1', 'child1', 'child2', 'child3'],
'mother2': ['child1', 'child2', 'child1', 'child1', 'child2', 'child3'],
'mother3': ['child1', 'child2', 'child1', 'child1', 'child2', 'child3']}