gpt4 book ai didi

python - 一个数据帧中的值是否在另一个数据帧的容器中?

转载 作者:太空宇宙 更新时间:2023-11-03 16:36:55 25 4
gpt4 key购买 nike

我有一个名为 loc_df 的数据框,其中包含两列 bin,如下所示...

> 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

我想在数据中创建一个新的 bool 列,以显示 loc_x 是否在 loc_x_bin 的值内,以及 loc_y 是否在 的值内数据帧 loc_df 的 >loc_y_binloc_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_bin loc_y_bin 不在同一行,所以我希望这是错误的。

最佳答案

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_bin并且y属于 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

关于python - 一个数据帧中的值是否在另一个数据帧的容器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com