【发布时间】:2022-07-13 01:15:34
【问题描述】:
我正在尝试规范化从我的数据库中提取的数据。在这些数据中有一个名为ExtraData 的列,它以嵌套的json 表示。我的ExtraData JSON 可能是这些情况之一:
{"Data":{"Parties":[{"ID":"JackyID","Role":12}],"NbIDs":1}} #One party identified
{"Data":{"Parties":[{"ID":"JackyID","Role":12},{"ID":"SamNumber","Role":10}],"NbIDs":2}} #Two Parties identified
{"Data":{"Parties":[],"NbIDs":0}} #No parties identified
{"Data": None} #No data
当要提取 ID(当事方的 ID - String 数据类型)和 Role(Int 数据类型 - 当 Role=12 时指买家,当 Role=10 时指卖家)的值时,当什么都不存在时写“”,我'正在使用以下方法:
def parse_extra_data(data_str):
response = {'Buyer': '', 'Seller': ''}
try:
data_json = json.loads(data_str)
except:
return response
for party in data_json['Data']['Parties']:
if party['Role'] == 12:
response['Buyer'] = party['ID']
elif party['PartyRole'] == 122:
response['Seller'] = party['ID']
return response
现在,当我想将此方法应用于我的代码时:
import json
import pandas.io.json as pd_json
query="SELECT OrderID, ExtraData from tbl_data;"
test_data= crsr.execute(query)
columns_test = [column[0] for column in crsr.description]
rows = [list(x) for x in test_data]
df = pd.DataFrame(rows, columns=columns_test)
for i,row in df.iterrows():
test = json.dumps(row['Data'])
data = pd_json.loads(test)
data_json = json.loads(data)
df['Buyer'] = df.apply(lambda row: parse_extra_data(data_json['Data'])['Buyer'], axis=1)
df['Seller'] = df.apply(lambda row: parse_extra_data(data_json['Data'])['Seller'], axis=1)
df.rename(columns={
'OrderID' :'ID of the order'
}, inplace = True)
df = df[['ID of the order','Buyer', 'Seller']]
执行这段代码时,df如下:
>>print(df)
ID of the order |Buyer | Seller
--------------------------------------
321 | |
456 | |
789 | |
987 | |
而print(data_json) 仅显示来自ExtraData 的第一个 JSON。
我做错了什么?以及如何解决?如果我们把上面的场景作为数据库输入,df 应该是这样的:
>>print(df)
ID of the order |Buyer | Seller
---------------------------------------
321 |JackyID| #Transaction 1 we have info about the buyer
456 |JackyID| SamNumber #Transaction 2 we have infos about the buyer and the seller
789 | | #Transaction 3 we don't have any infos about the parties
987 | | #Transaction 4 we don't have any infos about the parties
【问题讨论】: