我有两个 pandas Dataframe,使用 python3.x:
import pandas as pd
dict1 = {0:['chr1','chr1','chr1','chr1','chr2'],
1:[1, 100, 150, 900, 1], 2:[100, 200, 500, 950, 100],
3:['feature1', 'feature2', 'feature3', 'feature4', 'feature4'],
4:[0, 0, 0, 0, 0], 5:['+','+','-','+','+']}
df1 = pd.DataFrame(dict1)
print(df1)
## 0 1 2 3 4 5
## 0 chr1 1 100 feature1 0 +
## 1 chr1 100 200 feature2 0 +
## 2 chr1 150 500 feature3 0 -
## 3 chr1 900 950 feature4 0 +
## 4 chr2 1 100 feature4 0 +
dict2 = {0:['chr1','chr1'], 1:[155, 800], 2:[200, 901],
3:['feature5', 'feature6'], 4:[0, 0], 5:['-','+']}
df2 = pd.DataFrame(dict2)
print(df2)
## 0 1 2 3 4 5
## 0 chr1 155 200 feature5 0 -
## 1 chr1 800 901 feature6 0 +
这些数据框中要关注的列是前三列:位置、开始和结束。每个开始:结束值代表位置上的距离(例如,chr1
、chr2
、chr3
)。
我想输出 df1
与 df2
的交集。这是正确的输出:
chr1 155 200 feature2 0 +
chr1 155 200 feature3 0 -
chr1 900 901 feature4 0 +
解释:我们找到 df1
与 df2
的交集。因此,feature2
和 feature3
与 df2
相交于 155 到 200。feature4
与 df2
重叠900 到 901。
找到交叉点最有效的方法是什么(就运行时间和 RAM 而言)?
编辑:有一个Python包在这里做类似的事情:https://daler.github.io/pybedtools/intersections.html
最佳答案
import pandas as pd
df1 = pd.DataFrame({0:['chr1','chr1','chr1','chr1','chr2'],
1:[1, 100, 150, 900, 1], 2:[100, 200, 500, 950, 100],
3:['feature1', 'feature2', 'feature3', 'feature4', 'feature4'],
4:[0, 0, 0, 0, 0], 5:['+','+','-','+','+']})
df2 = pd.DataFrame({0:['chr1','chr1'], 1:[155, 800], 2:[200, 901],
3:['feature5', 'feature6'], 4:[0, 0], 5:['-','+']})
您可以使用apply
和一些逻辑测试来查找重叠。不过,您必须循环遍历染色体组。您应该能够执行类似的操作来查找和修复需要调整的起点和终点。如果以后有时间我会写一些东西。
new_dfs = []
for chr_name, chr_df in df1.groupby(0):
chr_df2 = df2.loc[df2[0] == chr_name]
overlapping = (chr_df[1].apply(lambda x: chr_df2[2] >= x) & chr_df[2].apply(lambda x: chr_df2[1] <= x)).any(axis=1)
new_dfs.append(chr_df.loc[overlapping, :])
new_dfs = pd.concat(new_dfs)
总体而言,这将提高内存效率,但不是 super 快。如果您想要快速,您可能必须编写一些复杂的索引。
关于python - 使用pandas,找到两个DataFrame之间的相交区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101192/