我需要获取所有以side_a - side_b表示的链接的子代坐标(在一个数据帧中),直到达到每个side_a的end_point为止(在另一个数据帧中)。因此:
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
目标是从df2中获取对于每个side_a值的所有点,直到达到end_point。如果它具有两个end_point值(例如"k"),则应该有两个列表。
我有一些代码,但它没有按照这种方法编写,它会删除所有df1中的行,如果df1['side_a'] == df2['end_points']
,这会导致某些问题。但是如果有人想要我发布代码,当然可以。
期望的输出类型可能类似于这样:
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,则停止,不再继续。任何帮助或提示在这里都受到欢迎,真的谢谢你们。提前致谢。
df2
中有一个拼写错误:q
的end_point
应该是r
,而不是s
。我可能有一个简单的解决方案来解决你的问题,但它在大型数据框上的性能不佳。你的数据框大约有多大? - Qusai Alothmand
不是a
、b
和c
的终点(或“后代”)吗? - JohnE