gpt4 book ai didi

python - 如何确定 Pandas DataFrame 中给定 x 和 y 坐标列的象限

转载 作者:行者123 更新时间:2023-12-05 09:30:44 24 4
gpt4 key购买 nike

数据框格式:

<表类="s-表"><头> dentry 编号x_centery_center宽度高度象限<正文>10.3096430.0825200.0723250.1694762-0.211200-0.0576750.0713210.1996453-0.307634-0.1277730.0813660.1872234-0.262933-0.0936110.0652940.21118050.2531390.1366460.0969360.190772

问题:如何编写一个循环来传递以下结果?在每一卷中:

if x_center >=0 and y_center >= 0, quadrant = 1
if x_center <0 and y_center >= 0, quadrant = 2
if x_center <0 and y_center <0, quadrant = 3
if x_center >0 and y_center <0, quadrant = 4

最佳答案

解决方案

这是另一个解决方案,使用 arctan2 和一些模块化算法。请注意,Corralien 的方法更具普遍性。以下内容非常针对此用例。

import numpy as np

deg = np.round(180 * np.arctan2(df.y_center, df.x_center) / np.pi).astype(int)
df["quadrant"] = 1 + ((deg + 360) % 360) // 90

输出:

>>> df
tooth_id x_center y_center width height quadrant
0 1 0.309643 0.082520 0.072325 0.169476 1
1 2 -0.211200 -0.057675 0.071321 0.199645 3
2 3 -0.307634 -0.127773 0.081366 0.187223 3
3 4 -0.262933 -0.093611 0.065294 0.211180 3
4 5 0.253139 0.136646 0.096936 0.190772 1

请注意,轴上的点沿逆时针方向“滚动”到相邻象限,例如,位于 90° 的点 (0, 0.631) 被视为象限2; (-0.578, 0),位于 180° 处被认为是象限 3,等等。

步骤

使用 np.arctan2() 获取每个 (x, y) 点形成的角度(以度为单位):

>>> deg = np.round(180 * np.arctan2(df.y_center, df.x_center) / np.pi).astype(int)
>>> deg
0 15
1 -165
2 -157
3 -160
4 28
dtype: int32

现在,将 (-180°, 180°] 转换为 [0°, 360°):

>>> deg = (deg + 360) % 360
>>> deg
0 15
1 195
2 203
3 200
4 28
dtype: int32

楼层除以 90 得到象限(将返回 0、1、2、3 —— 所以还要加 1):

>>> quadrant = 1 + (deg // 90)
>>> quadrant
0 1
1 3
2 3
3 3
4 1
dtype: int32

关于python - 如何确定 Pandas DataFrame 中给定 x 和 y 坐标列的象限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69398528/

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