如何在DataFrame中基于中心坐标与偏移元组生成精确坐标列
解决方案
你可以通过Pandas的apply函数逐行处理数据,将圆心坐标与每个偏移量相加,生成精确坐标元组。以下是具体实现步骤:
1. 构造示例数据(已有目标DataFrame可跳过)
import pandas as pd data = { 'X coordinate': [400, 500, 450, 525, 475, 510], 'Y coordinate': [450, 550, 250, 800, 360, 550], 'Offset': [ ((4, 1),(2, 1),(1, 1),(1, 2),(1, 3),(-4, 4)), ((7, 1),(4, 2),(3, 0),(-2, 1),(-4, 1),(0, 3)), ((4, 1),(2, 1),(1, 1),(1, 2),(1, 3),(-4, 4)), ((7, 1),(4, 2),(3, 0),(-2, 1),(-4, 1),(0, 3)), ((4, 1),(2, 1),(1, 1),(1, 2),(1, 3),(-4, 4)), ((7, 1),(4, 2),(3, 0),(-2, 1),(-4, 1),(0, 3)) ] } df = pd.DataFrame(data)
2. 生成精确坐标列
使用apply结合lambda函数,遍历每行的偏移量元组,计算每个点的精确坐标:
df['Exact Coordinates'] = df.apply( lambda row: tuple( (row['X coordinate'] + x_off, row['Y coordinate'] + y_off) for x_off, y_off in row['Offset'] ), axis=1 )
3. 查看结果
执行后,Exact Coordinates列即为所需的精确坐标元组。你可以通过以下代码查看结果:
print(df[['X coordinate', 'Y coordinate', 'Exact Coordinates']])
示例输出(第一行)
| X coordinate | Y coordinate | Exact Coordinates |
|---|---|---|
| 400 | 450 | ((404, 451), (402, 451), (401, 451), (401, 452), (401, 453), (396, 454)) |
内容的提问来源于stack exchange,提问作者dennis vlaar
相关产品推荐
相关产品推荐

