子集数据帧与另一个不同长度的数据帧

时间:2017-05-11 03:41:36

标签: python pandas numpy genome

我有一个数据框,其中染色体(chr)表示相互作用的染色体对,位置(pos)如下:

>>>import pandas as pd

>>>df1
chr1     pos1     chr2     pos2
chr1    54278    chr13    68798
chr1    32145     chr7  1248798
... 
[162689366 rows x 4 columns]

在真实数据集中,这些数据按chr1排序,然后是pos1,chr2,pos2。

我有另一个数据集,其中包含我希望以下列格式查看的交互对:

>>>df2
chr     start     stop     comment
chr1    54275    55080   cluster-1
chr1   515523   515634   cluster-2
...
chr13   68760    70760
...
[69 rows x 4 columns]

我希望将df1子集包含行,当且仅当在df2中的起始值和停止值范围内找到两个交互对(chr1-pos1& chr2-pos2)时。

在这个例子中,最终的数据框看起来像这样:

>>>df3
chr1    pos1      chr2     pos2
chr1    54278    chr13    68798
...

我一直试图在pandas中使用.between函数而没有任何成功地执行此步骤(对于第一个chr-pos对,然后是第二个)。我已经尝试过python2.7和python3.6。

>>>df3 = df1[(df1['chr1'].isin(df2.chr)) & df1['pos1'].between(df1.pos1(df2.start),df1.pos1(df2.stop))]

这似乎适用于.isin,但我得到.between函数的错误。我认为因为数据帧的长度不一样,但我不能确定。

>>>df1['pos1'].between(df2.start,df2.stop)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/pandas/core/series.py", line 2412, in between
    lmask = self >= left
  File "/usr/lib/python2.7/dist-packages/pandas/core/ops.py", line 699, in wrapper
    raise ValueError('Series lengths must match to compare')
ValueError: Series lengths must match to compare

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

有人可能会有更优雅的解决方案,但在我的脑海中,我会将df2加入df1两次,这样您就可以将所有内容都放在一个数据集中,并且比较很容易。

df2基本上是一个查找表,df2.chr应该分别与df1.chr1df1.chr2匹配。

df_all = df1.merge(df2,
                   how='inner',
                   left_on='chr1',
                   right_on='chr') \
            .merge(df2,
                   how='inner',
                   left_on='chr2',
                   right_on='chr',
                   suffixes=('_r1', '_r2'))

注意后缀。因此pos1将在start_r1 - stop_r1范围内进行测试,pos2将在start_r2 - stop_r2中进行测试范围。

df3 = df_all[(df_all['pos1'] \
                  .between(df_all['start_r1'], df_all['stop_r1'])) &
             (df_all['pos2'] \
                  .between(df_all['start_r2'], df_all['stop_r2']))]

# Back to four original columns again
df3 = df3[['chr1', 'pos1', 'chr2', 'pos2']]