通过将一列的所有值与另一个数据帧的列的全部值进行比较来对数据帧进行切片



我有一个关于切片数据帧的问题。我有两个数据帧:索引为3447、4024…的halo_field

H_masa  N_subs      ...                 H_z             rh
3447  1.066437e+11       1      ...        88419.632812  160354.430049
4024  4.423280e+11       1      ...        49013.289062   65239.433084
4958  3.171903e+11       1      ...        23239.701172   48248.401956
5749  2.817211e+11       1      ...        46585.765625   65032.216212
6512  2.471275e+11       1      ...        93403.398438  123058.838527

我有一个数据帧subhalo,其中一列名为"halo_index",索引到数据帧halo中,halo_field是其中的切片(因此我们有这样的halo_field索引(-这是subhalo.halo_index的打印输出(右侧(:

0                0
1                0
2                0
3                0
4                0
...   
4366516    7713551
4366517    7713552
4366518    7713553

我想将subhalo数据帧分割到数据帧subhalo_field中,这样它只包含具有halo_index列值的行,该列值也包含在halo_field.index中。问题是,这两列的长度当然不相同,我不能这样做(比较行与行与比较一列的所有值与另一列的全部值(:

subhalo_field=subhalo[subhalo.halo_index==halo_field.index].copy()

我得到这个错误:

File "group_sh.py", line 139, in <module>
subhalo_field=subhalo[subhalo.halo_index==halo_field.index].copy()
File "/usr/local/lib/python2.7/dist-packages/pandas/core/ops.py", line 1223, in wrapper
raise ValueError('Lengths must match to compare')
ValueError: Lengths must match to compare

如何对subhalo数据帧进行切片,以便将subhalo.halo_index与halo_field.index进行比较,并将这些subhalo复制到具有加工halo_index和halo_field_index的subhalo_fields中?

如果我理解正确,halo_field的索引上的mergesubhalohalo_index列可能就是您想要的(这默认为内部联接行为(:

halo_field.merge(subhalo, left_index=True, right_index=False, right_on='halo_index')

我找到了解决方案:

subhalo_field=subhalo[subhalo.halo_index.isin(halo_field.index)].copy()

最新更新