一个数据帧中的值是否位于另一个数据帧的二进制位中?

时间:2016-05-09 21:09:28

标签: python pandas

我有一个名为loc_df的数据框,其中有两列看起来像这样的列......

> loc_df

loc_x_bin        loc_y_bin      
(-20, -10]        (0, 50]           
(-140, -130]      (100, 150]        
(0,  10]          (-50, 0]          

我有另一个名为data的数据框,看起来像这样......

> data

  loc_x         loc_y  
   -15            25
    30            35
    5            -45
   -135          -200

我想在数据中创建一个新的布尔列,显示loc_x是否在loc_x_binloc_y的值内是否在loc_y_bin的数据帧loc_df内}}。 loc_xloc_y必须位于同一行的loc_x_binloc_y_bin中。例如:

> data

 loc_x          loc_y         in_bins
  -15             25             true
   30             35             false
   5             -45             true
  -135           -200            false
   5              25             false**

更新 **虽然5在(0,10)loc_x_bin范围内且25在(0,50)loc_y_bin范围内,但loc_x_binloc_y_bin不在同一行我希望这是假的。

1 个答案:

答案 0 :(得分:1)

UPDATE2:,如果您想检查 xy是否属于df_loc中同一行的容器 (或loc_df):

xstep = 10
ystep = 50

In [201]: (df.assign(bin=(pd.cut(df.loc_x, np.arange(-500, 500, xstep)).astype(str)
   .....:                 +
   .....:                 pd.cut(df.loc_y, np.arange(-500, 500, ystep)).astype(str)
   .....:                )
   .....:           )
   .....: )['bin'].isin(df_loc.sum(axis=1))
Out[201]:
0     True
1    False
2     True
3    False
4    False
Name: bin, dtype: bool

说明:

In [202]: (df.assign(bin=(pd.cut(df.loc_x, np.arange(-500, 500, xstep)).astype(str)
   .....:                 +
   .....:                 pd.cut(df.loc_y, np.arange(-500, 500, ystep)).astype(str)
   .....:                )
   .....:           )
   .....: )
Out[202]:
   loc_x  loc_y                       bin
0    -15     25         (-20, -10](0, 50]
1     30     35           (20, 30](0, 50]
2      5    -45           (0, 10](-50, 0]
3   -135   -200  (-140, -130](-250, -200]
4      5     25            (0, 10](0, 50]

In [203]: df_loc.sum(axis=1)
Out[203]:
0         (-20, -10](0, 50]
1    (-140, -130](100, 150]
2           (0, 10](-50, 0]
dtype: object

更新:如果您想检查x是否属于loc_x_biny是否属于loc_y_bin(不一定来自同一行)在df_loc):

如果df_loc.dtypes没有为这两列显示category,那么您可能希望首先将类别转换为category dtype:

df_loc.loc_x_bin = df_loc.loc_x_bin.astype('category')
df_loc.loc_y_bin = df_loc.loc_y_bin.astype('category')

然后您可以动态对df中的列进行分类”:

xstep = 10
ystep = 50

df['in_bins'] = (   (pd.cut(df.loc_x, np.arange(-500, 500, xstep)).isin(df_loc.loc_x_bin))
                    &
                    (pd.cut(df.loc_y, np.arange(-500, 500, ystep)).isin(df_loc.loc_y_bin))
                )

测试:

In [130]: df['in_bins'] = (   (pd.cut(df.loc_x, np.arange(-500, 500, xstep)).isin(df_loc.loc_x_bin))
   .....:                     &
   .....:                     (pd.cut(df.loc_y, np.arange(-500, 500, ystep)).isin(df_loc.loc_y_bin))
   .....:                 )

In [131]: df
Out[131]:
   loc_x  loc_y in_bins
0    -15     25    True
1     30     35   False
2      5    -45    True
3   -135   -200   False