【问题标题】:Slicing dataframe by comparing all values of one column to all values of column of another dataframe通过将一列的所有值与另一数据帧的列的所有值进行比较来切片数据帧
【发布时间】:2019-04-01 21:06:21
【问题描述】:

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

           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_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 中?

【问题讨论】:

    标签: python pandas dataframe slice


    【解决方案1】:

    如果我理解正确,halo_field 的索引上的 mergesubhalohalo_index 列可能是您正在寻找的(这默认为内部连接行为):

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

    【讨论】:

    • 试过了,但从 subhalo 数据帧的长度来看,我发现这不是我需要的。我需要比较 halo_field.index 和 subhalo.halo_index 并将 subhalo 数据帧中 halo_index 值与 halo_field.index 中的某个值匹配的那些 subhalo 复制到 subhalo_field 数据帧。例如,我可以有 halo_field.index 的值 3440,然后我想将该值与 subhalo.halo_index 的值进行比较,假设我的五个 subhalo 具有 subhalo.halo_index=3440,然后将这五个 subhalo 复制到数据帧 subhalo_field。我想对 halo_field.index 的每个值都这样做。
    【解决方案2】:

    我找到了解决办法:

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

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多