[英]How to create a dataframe from a list of tuples?
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].我正在尝试创建上述数据的数据框,但问题是 q1 中的第二个元组没有 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)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.