I have some data that I want to expand into new columns. The data looks like:
id d
0 403 {'cases': 1, 'suspects': 22, 'negative': 0, 's', ...}
1 402 {'cases': 0, 'suspects': 18, 'negative': 0, 's', ...}
2 401 {'cases': 0, 'suspects': 31, 'negative': 0, 's', ...}
I am trying to get it such that the nested column d is spread out into new columns. I can get some of the data from d using:
rows = []
for i, row in myDF.iterrows():
for stat in row['d']['stats']:
new_row = {
**row.to_dict(),
**stat,
}
rows.append(new_row)
However I cannot get it all. How can I extract the objects such that I have a new column with the corresponding cases as the observations?
Expected Output (column names do not have to be exact):
cases suspects negative diag_casesELISA_sex_F diag_suspects_sex_M diag_suspects_sex_F diag_suspectsPCR_sex_F diag_suspectsPCR_sex_M
1 22 0 1 11 10 1 NA
0 18 0 NA 9 9 NA NA
0 31 0 NA 12 18 NA 1
Data:
myDF = pd.DataFrame.from_dict({'id': {0: '403', 1: '402', 2: '401'}, 'd': {0: {'cases': 1, 'suspects': 22, 'negative': 0, 'stats': [{'diag': 'casesELISA', 'sex': 'F', 'cases': 1}, {'diag': 'suspects', 'sex': 'M', 'cases': 11}, {'diag': 'suspects', 'sex': 'F', 'cases': 10}, {'diag': 'suspectsPCR', 'sex': 'F', 'cases': 1}]}, 1: {'cases': 0, 'suspects': 18, 'negative': 0, 'stats': [{'diag': 'suspects', 'sex': 'M', 'cases': 9}, {'diag': 'suspects', 'sex': 'F', 'cases': 9}]}, 2: {'cases': 0, 'suspects': 31, 'negative': 0, 'stats': [{'diag': 'suspects', 'sex': 'M', 'cases': 12}, {'diag': 'suspects', 'sex': 'F', 'cases': 18}, {'diag': 'suspectsPCR', 'sex': 'M', 'cases': 1}]}}})