[英]How to reproduce the same output of foverlaps in R with merge of pandas in python?
我正在使用foverlaps函數在表格的R中進行合並。 但我需要使用python重現相同的輸出。 我做了一個搜索,我在pandas庫上找到了合並功能。 但即使使用此功能,我也無法重現相同的輸出。
首先是R中的輸出:
這是第一個表(間隔):
V1 V2 intid
1: 1 5 1
2: 4 9 2
3: 6 12 3
4: 11 17 4
5: 18 20 5
這是第二個表(decomp):
V1 V2 subid
1: 1 4 A
2: 4 5 B
3: 5 6 C
4: 6 9 D
5: 9 11 E
6: 11 12 F
7: 12 17 G
8: 17 18 H
9: 18 20 I
R中的代碼進行合並:
relations <- foverlaps(decomp, intervals, type='within', nomatch=0)
輸出(關系):
V1 V2 intid i.V1 i.V2 subid
1: 1 5 1 1 4 A
2: 1 5 1 4 5 B
3: 4 9 2 4 5 B
4: 4 9 2 5 6 C
5: 4 9 2 6 9 D
6: 6 12 3 6 9 D
7: 6 12 3 9 11 E
8: 6 12 3 11 12 F
9: 11 17 4 11 12 F
10: 11 17 4 12 17 G
11: 18 20 5 18 20 I
現在我在python中的輸出:
這是第一個表(df_of_pairs):
V1 V2 intid
0 1 5 1
1 4 9 2
2 6 12 3
3 11 17 4
4 18 20 5
這是第二個表(df_of_adjacent):
V1 V2 subid
0 1 4 A
1 4 5 B
2 5 6 C
3 6 9 D
4 9 11 E
5 11 12 F
6 12 17 G
7 17 18 H
8 18 20 I
現在是問題 ,當我使用pandas merge時,我沒有在python中重現相同的輸出。 我嘗試了幾種方式,但是我沒有成功,這是我使用它的方法之一:
df = df_of_pairs.merge(df_of_adjacent, left_on=['V1'], right_on=['V2'] )
輸出(df):
V1_x V2_x intid V1_y V2_y subid
0 4 9 2 1 4 A
1 6 12 3 5 6 C
2 11 17 4 9 11 E
3 18 20 5 17 18 H
這個問題與Python中的R foverlaps非常相似,但在這種情況下它有不同的列。
我無法輕松獲得您想要的輸出,但這是使用IntervalIndex
的部分解決方案。
s1 = pd.IntervalIndex.from_arrays(df1['V1'], df1['V2']) # default: closed='right'
s2 = pd.IntervalIndex.from_arrays(df2['V1'], df2['V2'])
df_of_adjacent.set_index(s2, inplace=True)
df_of_adjacent.loc[s1]
V1 V2 subid
(1, 4] 1 4 A
(4, 5] 4 5 B
(4, 5] 4 5 B
(5, 6] 5 6 C
(6, 9] 6 9 D
(6, 9] 6 9 D
(9, 11] 9 11 E
(11, 12] 11 12 F
(11, 12] 11 12 F
(12, 17] 12 17 G
(18, 20] 18 20 I
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.