摘要
简而言之,我需要从包含单个OrderedDicts的pandas系列中提取数据。到目前为止进展不错,但我现在遇到了一个绊脚石。你知道吗
当我在堆栈溢出上定义自己的数据帧用于演示时,我能够使用orderedict索引功能在orderedict中查找我要查找的数据。但是,当我处理实际数据时,如果我没有在dataframe中定义orderedict,我必须使用函数通过标准Json包解析orderedict。你知道吗
我正在处理的OrderedDicts有多个嵌套层次结构,可以用通常的方式操作。。。你知道吗
from collections import OrderedDict
example = OrderedDict([('attributes', OrderedDict([('type', 'Name'), ('url', 'URLHERE')])), ('UserRole', OrderedDict([('attributes', OrderedDict([('type', 'UserRole'), ('url', 'URLHERE')])), ('Name', 'Telephone Sales')]))])
print(example['UserRole']['Name'])
上面的代码将导致'Telephone Sales'
。但是,这仅在我为示例手动定义了DataFrame时有效,因为我必须使用收藏.订购信息不需要解析的包。你知道吗
背景
下面是我为StackOverflow准备的一些代码,它松散地演示了我的问题。你知道吗
import pandas as pd
import json
from collections import OrderedDict
# Settings
pd.set_option('display.max_colwidth', -1)
# Functions
def extract_odict_item(odict, key_1, key_2=None):
data = json.dumps(odict)
final_data = json.loads(data)
if key_2 is None:
if final_data is not None:
return final_data[key_1]
else:
return None
elif key_2 is not None:
if final_data is not None:
return final_data[key_1][key_2]
else:
return None
# Data
accounts = [
OrderedDict([('attributes', OrderedDict([('type', 'Account'), ('url', 'URLHERE')])), ('Name', 'Supermarket'), ('AccountNumber', 'ACC1234'), ('MID__c', '123456789')]),
OrderedDict([('attributes', OrderedDict([('type', 'Account'), ('url', 'URLHERE')])), ('Name', 'Bar'), ('AccountNumber', 'ACC9876'), ('MID__c', '987654321')]),
OrderedDict([('attributes', OrderedDict([('type', 'Account'), ('url', 'URLHERE')])), ('Name', 'Florist'), ('AccountNumber', 'ACC1298'), ('MID__c', '123459876')])
]
owner = [
OrderedDict([('attributes', OrderedDict([('type', 'Name'), ('url', 'URLHERE')])), ('UserRole', OrderedDict([('attributes', OrderedDict([('type', 'UserRole'), ('url', 'URLHERE')])), ('Name', 'Telephoone Sales')]))]),
OrderedDict([('attributes', OrderedDict([('type', 'Name'), ('url', 'URLHERE')])), ('UserRole', OrderedDict([('attributes', OrderedDict([('type', 'UserRole'), ('url', 'URLHERE')])), ('Name', 'Field Sales')]))]),
OrderedDict([('attributes', OrderedDict([('type', 'Name'), ('url', 'URLHERE')])), ('UserRole', OrderedDict([('attributes', OrderedDict([('type', 'UserRole'), ('url', 'URLHERE')])), ('Name', 'Online Sale')]))])
]
# Dataframe
df = pd.DataFrame({'ConvertedAccounts': accounts,
'Owner': owner
})
# Extract data from OrderedDict using usual indexing
df['MerchantID'] = df['ConvertedAccounts'].apply(lambda x: x['MID__c'])
df['UserRole'] = df['Owner'].apply(lambda x: x['UserRole']['Name'])
# Extract data from OrderedDict using function
df['extracted_MerchantID'] = df['ConvertedAccounts'].apply(lambda x: extract_odict_item(x, 'MID__c'))
df['extracted_UserRole'] = df['Owner'].apply(
lambda x: extract_odict_item(x, 'UserRole', 'Name'))
# Drop junk columns
df = df.drop(columns=['ConvertedAccounts', 'Owner'])
print(df)
在上面的代码中,我有一个函数extract\u odict\u item(),我可以用它从dataframe中的每个orderedict中提取数据,并将其放入一个新的列中,只要我指定了我想要的内容。但是,我希望能够通过*args指定尽可能多的参数,以表示要遍历多少个嵌套,并从最终键中提取值。你知道吗
预期结果
我希望能够使用下面的函数来接受多个参数并创建一个嵌套的索引选择器,就像这样。。。你知道吗
# Functions
def extract_odict_item(odict, *args):
data = json.dumps(odict)
final_data = json.loads(data)
if len(args) == 0:
raise Exception('Requires atleast 1 argument')
elif len(args) == 1:
if final_data is not None:
return final_data[args[0]]
else:
return None
elif len(args) > 1:
### Pseudo Code ###
# if final_data is not None:
# return final_data[args[0]][args[1]][args[2]] etc.....
# else:
# return None
所以如果我叫extract\u odict\u item
extract_odict_item(odict, 'item1', 'item2', 'item3')
它应该返回final_data['item1']['item2']['item3']
我可能已经把它复杂化了,但是我想不出任何其他的东西,或者这在Python中是否是可能的。你知道吗
回答
我能够使用递归函数来处理从ordereddict中选择需要的数据
import json
from collections import OrderedDict
# Settings
pd.set_option('display.max_colwidth', -10)
# Data
owner = [
OrderedDict([('attributes', OrderedDict([('type', 'Name'), ('url', 'URLHERE')])), ('UserRole', OrderedDict([('attributes', OrderedDict([('type', 'UserRole'), ('url', 'URLHERE')])), ('Name', 'Telephoone Sales')]))]),
OrderedDict([('attributes', OrderedDict([('type', 'Name'), ('url', 'URLHERE')])), ('UserRole', OrderedDict([('attributes', OrderedDict([('type', 'UserRole'), ('url', 'URLHERE')])), ('Name', 'Field Sales')]))]),
OrderedDict([('attributes', OrderedDict([('type', 'Name'), ('url', 'URLHERE')])), ('UserRole', OrderedDict([('attributes', OrderedDict([('type', 'UserRole'), ('url', 'URLHERE')])), ('Name', 'Online Sale')]))])
]
# Functions
def rec_ext(odict, item_list):
new_list = item_list.copy()
data = json.dumps(odict)
final_data = json.loads(data)
el = new_list.pop()
if isinstance(final_data[el], dict):
return rec_ext(final_data[el], new_list)
else:
return final_data[el]
# Dataframe
df = pd.DataFrame({'owner': owner
})
my_columns = ['UserRole', 'Name']
my_columns.reverse()
df['owner2'] = df['owner'].apply(lambda x: rec_ext(x, my_columns))
print(df['owner2'])
这不是一个确切的答案-但你可以尝试递归,如果我理解你的问题正确-
相关问题 更多 >
编程相关推荐