我有以下元組串列:
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)'},)]
我正在嘗試創建上述資料的資料框,但問題是 q1 中的第二個元組沒有 tup[2]。所以我需要找到一種方法來忽略與第一個布局不同的元組......
當我運行下面的代碼時,出現以下錯誤:
df1 = pd.DataFrame.from_records([create_record(record)for tup in q1 for record in tup[2]])
IndexError: tuple index out of range
這是我的代碼:
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)
uj5u.com熱心網友回復:
嘗試:
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)
輸出
ResultID
0 1
1 2
2 3
3 4
4 5
5 6
6 7
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347421.html
上一篇:了解容器的好資源
