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

标签 python pandas for-loop where-clause

数据框格式:

<表类="s-表"> <头> 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

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

相关文章:

python win32com 导致程序崩溃

python - Python 中的 R 风格负索引。不要切片

python - 在组内排序并添加指示下方和上方行的列

python - pandas - 计算列中值的使用

Python 效率 - 比多个 if elif 语句更好的版本 - 使用 for 循环 - chr ord 转换?

python - 将第一个数组的每个元素与第二个数组的所有元素相加

Python Gtk 按钮

pandas - 如果列值在数据框中没有出现一定的次数,如何随机复制行直到满足该计数?

c - 如何在 C 中用零填充和取消填充 2D 矩阵?

C程序在if语句中覆盖文件内容