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

数据框格式:

dentry 编号 x_center y_center 宽度 高度 象限 1 0.309643 0.082520 0.072325 0.169476 2 -0.211200 -0.057675 0.071321 0.199645 3 -0.307634 -0.127773 0.081366 0.187223 4 -0.262933 -0.093611 0.065294 0.211180 5 0.253139 0.136646 0.096936 0.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

https://stackoverflow.com/questions/69398528/

相关文章:

reactjs - 保存我的代码时 Eslint 配置错误

kotlin-coroutines - Kotest 与 kotlinx-coroutines-te

c++ - 在 C++ 中的 unordered_map 中排序

nestjs - 嵌套类验证器 minDate 即使日期更大也会抛出错误

r - 根据 R 中表格的列数过滤列表

list - Groovy:比较列表忽略其中元素的顺序

python - 在不添加额外列的情况下创建颜色基于年份的散点图

c# - 如何在 dotnet 中将 ""解析为 long ("0")

python - 使用 matplotlib 3.3+ 更改颜色条限制以更改比例

css - Material-UI 下拉列表在对话框中溢出