I'm reading data from 2 csv using pandas read_csv
.
Details.csv
ID,VALID
P1,Yes
P2,No
P3,Yes
P4,No
Relations.csv
ParentID,ChildID
P1,C1
P1,C2
C1,C1A
C2,C2A
C1A,C1AA
P2,D1
P2,D2
D2,D2A
D2A,D2AA
P3,C4
P4,C5
Now i stored both in separate dataframes. I have to check the ID's from Details
in Relationship
and for each ID
find all level of its children(until no further child). If the ID has Yes
for VALID column, then all its child should have "VALID" if not then those are "NOT VALID".
Expected output
P1,VALID
C1,VALID
C2,VALID
C1A,VALID
C2A,VALID
C1AA,VALID
P2,NOT VALID
D1,NOT VALID
D2,NOT VALID
D2A,NOT VALID
D2AA,NOT VALID
P3,VALID
C4,VALID
P4,NOT VALID
C5,NOT VALID
Currently I'm doing this in SQL. I have no idea how to replicate this in python. Are there any functions available in pandas or I have to do with for
loop. Any suggestion would be appreciated.
From this question, i have tried something like below but it is not working.
import pandas as pd
details = pd.read_csv('C:/Myfolder/Python/Details.csv')
relationship = pd.read_csv('C:/Myfolder/Python/Relationship.csv')
def nlevel(details.id, parent_dict=relationship.ParentID, _cache={0:0}):
if details.id in _cache:
return _cache[details.id]
return 1+nlevel(parent_dict[details.id],parent_dict)