python - 从python中的数据框形成所有可能的路径(列表/字典)
问题描述
我正在尝试使用数据框形成所有可能的路径。我有以下数据框:
import pandas as pd
data = {'from': ['b','c','d','e','f','g'], 'to': ['a', 'a', 'a', 'b','c','e']}
df = pd.DataFrame.from_dict(data)
print(df)
样本数据框
现在,我想使用这 2 列创建所有可能的路径/链。输出应如下所示:
- e -> b -> a
- f -> c -> a
- g -> e -> b -> a
如果可能,然后用数字表示它们,例如:
- e -> b -> a = 5,2,1
- f -> c -> a = 6,3,1
- g -> e -> b -> a = 7,5,2,1
更新:发件人字段可以包含重复条目。
解决方案
# first of all let's make 'from' as index of df
df.set_index('from', inplace = True)
pth = []
def path(df, ch, res = []):
if ch in df.index:
path(df, df.loc[ch]['to'], res + [df.loc[ch]['to']])
else:
global pth
pth = res
return
import string # we will use it below for get character position in alphabet
for el in df.index:
path(df,el,[el])
print('->'.join(pth))
# when you speak about indexes, looks you want to get the character index in alphabet
# so here is my code
print([string.ascii_lowercase.index(i)+1 for i in pth])
print('')
Out[1]:
b->a
[2, 1]
c->a
[3, 1]
d->a
[4, 1]
e->b->a
[5, 2, 1]
f->c->a
[6, 3, 1]
g->e->b->a
[7, 5, 2, 1]
推荐阅读
- python - 使用python根据目录中的文件名读取文件的优化方法
- sqlite - sqlite 公用表表达式
- python-3.x - 第二个 QSizeGrip 到 QStatus 栏
- php - 提交带有某些俄语字符的表单时出现 404 错误
- python - 训练 SSD 给出 ValueError: Can't load save_path when it is None
- python - Pandas 按两列分组并在第三列中计算共享值
- json - 错误:尝试构建导航时 Dart 中未定义的名称“小部件”
- java - 减少java中的自定义对象列表
- python - aiohttp 抛出 nasdaq.com 的服务器断开连接
- json - 如何将对象转换为 Jooq JSON