【发布时间】:2020-02-19 13:55:57
【问题描述】:
我在 Pandas 数据框中有两列,它们的值在逻辑上彼此跟随。请参阅以下内容:
Name Includes
Account Product Account
Product Account Card Account
Card Account Plastic
Card Account Token
Token Token Vault
Account Savings Account
所以帐户>产品帐户>卡帐户等。最终我想创建一个列表列表,其中根(“帐户”)是每个列表的第一个元素。输出应如下所示:
[['Account', 'Product Account', 'Card Account', 'Plastic'],
['Account', 'Product Account', 'Card Account', 'Token', 'Token Vault'],
['Account', 'Savings Account']]
我基本上想找到可能存在的数据框元素之间的任何和所有可能的路径。我目前有一个将两个数据框列转换为字典结构的代码:
def link_hops(dictionary):
dictionary = dict(df.groupby('Name')['Includes'].apply(set))
dictionary = {k: list(v) for k, v in dictionary.items()}
all_values = set(x for xs in dictionary.values() for x in xs)
refs = all_values & set(dictionary.keys())
for k, v in dictionary.items():
for i in range(len(v)):
if v[i] in refs:
v[i] = {v[i]: v1 for k1, v1 in dictionary.items() if v[i] == k1}
dictionary = {k: v for k, v in dictionary.items() if k not in refs}
return dictionary
我得到以下信息:
{'Account': ['Savings Account',
{'Product Account': [{'Card Account': ['Plastic',
{'Token': ['Token Vault']}]}]}]}
此代码完成了定义从根('Account')到每个路径('Savings Account'、'Plastic'、'Token Vault')的终点存在的所有路径的工作,但我想不通了解如何将其转换为可扩展的列表格式。我有一个递归脚本,它确实适用于这样的小例子,但是当我通过link_hops 将它们转换为字典时,我正在使用的实际数据帧可能有数百或数千层深,并且很容易超过递归限制我称之为脚本。
我想知道是否可以跳过将我的数据框转换为字典的中间步骤,直接将其转换为列表列表,或者甚至只使用.map() 或类似的东西直接处理数据框。
【问题讨论】:
标签: python pandas list networkx