I have the following list of tuples:
q1 =[('energy level has been raised', 3317,
[{'ResultId': 1, 'CompletedOn': '2021-01-07T10:35:18.29 01:00', 'EnteredValue': None, 'EnteredOn': '2021-11-03T13:22:48.91 01:00', 'TextValue': None},
{'ResultId': 2, 'CompletedOn': '2021-01-07T10:38:19.12 01:00', 'EnteredValue': None, 'EnteredOn': '2021-11-03T13:28:11.267 01:00', 'TextValue': None},
{'ResultId': 3, 'CompletedOn': '2021-11-03T13:09:19.333 01:00', 'EnteredValue': None, 'EnteredOn': '2021-11-03T13:09:19.333 01:00', 'TextValue': None},
{'ResultId': 4, 'CompletedOn': None, 'EnteredValue': None, 'EnteredOn': None, 'TextValue': None},
{'ResultId': 5, 'CompletedOn': None, 'EnteredValue': None, 'EnteredOn': None, 'TextValue': None},
{'ResultId': 6, 'CompletedOn': None, 'EnteredValue': None, 'EnteredOn': None, 'TextValue': None},
{'ResultId': 7, 'CompletedOn': None, 'EnteredValue': None, 'EnteredOn': None, 'TextValue': None}],
'energy level has fallen down'),
({'code': '', 'message': 'Exception LS-27186:01 (4411459)'},)]
I'm trying to create a dataframe of above data but the problem is that the second tuple inside q1 does not have a tup[2]. So i need to find a way to ignore the tuples that dont have the same layout as the first one...
when I run below code I get the following error:
df1 = pd.DataFrame.from_records([create_record(record)for tup in q1 for record in tup[2]])
IndexError: tuple index out of range
This is my code:
def create_record(record):
pd_record = {
'ResultID': record['ResultId'],
}
df1 = pd.DataFrame.from_records([create_record(record)for tup in q1 for record in tup[2]])
print(df1.head)
CodePudding user response:
Try:
def create_record(record):
pd_record = {'ResultID': record['ResultId']}
return pd_record
df1 = pd.DataFrame.from_records([create_record(record) for tup in q1 if len(tup) > 1 for record in tup[2]])
print(df1)
Output
ResultID
0 1
1 2
2 3
3 4
4 5
5 6
6 7