【发布时间】:2018-04-17 20:40:13
【问题描述】:
我需要获取用 side_a - side_b 表示的链接的所有后代点(在一个数据帧中),直到到达每个 side_a 的端点(在另一个数据帧中)。所以:
df1:
side_a side_b
a b
b c
c d
k l
l m
l n
p q
q r
r s
df2:
side_a end_point
a c
b c
c c
k m
k n
l m
l n
p s
q s
r s
重点是获取每个 side_a 值的所有点,直到从 df2 到达该值的 end_point。 如果它有两个 end_point 值(如“k”),它应该是两个列表。
我有一些代码,但它不是用这种方法编写的,如果df1['side_a'] == df2['end_points'] 它会从 df1 中删除所有行,这会导致某些问题。但是,如果有人要我发布代码,我当然会。
想要的输出应该是这样的:
side_a end_point
a [b, c]
b [c]
c [c]
k [l, m]
k [l, n]
l [m]
l [n]
p [q, r, s]
q [r, s]
r [s]
还有一件事,如果两边相同,那一点根本不需要列出,我可以稍后再追加,不管它更容易。
import pandas as pd
import numpy as np
import itertools
def get_child_list(df, parent_id):
list_of_children = []
list_of_children.append(df[df['side_a'] == parent_id]['side_b'].values)
for c_, r_ in df[df['side_a'] == parent_id].iterrows():
if r_['side_b'] != parent_id:
list_of_children.append(get_child_list(df, r_['side_b']))
# to flatten the list
list_of_children = [item for sublist in list_of_children for item in sublist]
return list_of_children
new_df = pd.DataFrame(columns=['side_a', 'list_of_children'])
for index, row in df1.iterrows():
temp_df = pd.DataFrame(columns=['side_a', 'list_of_children'])
temp_df['list_of_children'] = pd.Series(get_child_list(df1, row['side_a']))
temp_df['side_a'] = row['side_a']
new_df = new_df.append(temp_df)
因此,如果我从 df2 中删除 side_a 等于 end_point 的行,则此代码的问题是有效。我不知道如何实现条件,如果在 side_b 列中捕获 df2,然后停止,不要进一步。
真的欢迎任何帮助或提示。 提前致谢。
【问题讨论】:
-
您当然记得它不是“请为我编写代码” 网站吗?你能向我们展示你的作品吗?您的代码的确切问题是什么?
-
@rsm 正如我所说,我可以发布我的代码,但它会使帖子变得巨大,我认为它不会被任何助手使用。你可以写一个我需要添加我的代码的评论,我会的,只是不要自大。
-
您能否向我们展示您的工作,添加您拥有的任何相关(!)代码?并解释你遇到的问题?如果您希望我们为您的问题提供算法和实现 - 这不是本网站的工作方式。
-
@jovicbg
df2中有一个错字:q的end_point应该是r,而不是s。对于您的问题,我可能有一个简单的解决方案,但它在大型数据帧上的性能不佳。您的数据框的大致大小是多少? -
@QusaiAlothman 谢谢,我已经编辑过了。这是一个很好的 ent_point,但我跳过了一步(q - r)。它不是很大,有 4000 行。
标签: python pandas recursion tree descendant