与 pandas 自我加入 [英] self-join with Pandas
本文介绍了与 pandas 自我加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对Pandas数据框执行自联接,以便将某些行附加到原始行。每行都有一个标记 i,指示应在右侧追加哪一行。
I would like to perform a self-join on a Pandas dataframe so that some rows get appended to the original rows. Each row has a marker 'i' indicating which row should get appended to it on the right.
d = pd.DataFrame(['A','B','C'], columns = ['some_col'])
d['i'] = [2,1,1]
In [17]: d
Out[17]:
some_col i
0 A 2
1 B 1
2 C 1
所需的输出:
some_col i some_col_y
0 A 2 C
1 B 1 B
2 C 1 B
也就是说,第2行附加到第0行,第1行附加到第1行,第1行附加到第2行(如i所示)。
That is, row 2 gets appended to row 0, row 1 to row 1, row 1 to row 2 (as indicated by i).
我的想法是
pd.merge(d, d, left_index = True, right_on = 'i', how = 'left')
但它会产生其他结果。
But it produces something else altogether. How to do it correctly?
推荐答案
加入
与 on ='i'
d.join(d.drop('i', 1), on='i', rsuffix='_y')
some_col i some_col_y
0 A 2 C
1 B 1 B
2 C 1 B
这篇关于与 pandas 自我加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文