You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问与管理pandas DataFrame列中的可迭代坐标数据?

解决方案

一、数据格式转换(推荐)

你提到的长表格式(x/y/z/image_name)是Pandas处理这类数据的最优结构,能大幅简化后续取值、筛选和转换操作。用以下代码可将现有JSON转换为该格式:

import pandas as pd

# 读取原始JSON
df = pd.read_json('img_data.json', orient='columns')

# 转换为长表格式
long_df = df.unstack().reset_index()
long_df.columns = ['image_name', 'index', 'coords']

# 拆分coords列到x/y/z
long_df[['x', 'y', 'z']] = pd.DataFrame(long_df['coords'].tolist(), index=long_df.index)

# 清理冗余列
long_df = long_df.drop(columns=['index', 'coords'])

转换后得到的long_df结构如下:

image_name    x    y             z
0    IMG1.tif  100  192  [129, 42, 32]
1    IMG1.tif  299  208  [133, 42, 24]
2    IMG2.tif  100  207  [128, 41, 34]
3    IMG2.tif  299  192   [81, 25, 26]

长格式下的便捷操作

  • 获取所有图像的y值:

    long_df.pivot(index=long_df.groupby('image_name').cumcount(), columns='image_name', values='y')
    

    输出:

    image_name  IMG1.tif  IMG2.tif
    0                192       207
    1                208       192
    
  • 获取单张图像的x值:

    long_df[long_df['image_name'] == 'IMG1.tif']['x']
    

    输出:

    0    100
    1    299
    Name: x, dtype: int64
    

二、原格式下的取值与转换

如果暂时无法修改数据格式,可通过自定义函数实现需求:

1. 获取指定轴的值

def get_axis_values(df, axis='x'):
    axis_map = {'x':0, 'y':1}
    idx = axis_map[axis]
    # 遍历每列提取对应位置的值
    result = df.apply(lambda col: col.apply(lambda lst: lst[idx]))
    return result

调用示例:

# 获取所有图像的y值
get_axis_values(df, 'y')

输出:

IMG1.tif  IMG2.tif
0       192       207
1       208       192

2. RGB转灰度值

采用标准公式0.2989*R + 0.5870*G + 0.1140*B实现转换:

def do_grayscale(df):
    def rgb_to_gray(lst):
        r, g, b = lst[2]
        gray = int(0.2989*r + 0.5870*g + 0.1140*b)
        return [lst[0], lst[1], gray]
    
    return df.apply(lambda col: col.apply(rgb_to_gray))

调用示例:

do_grayscale(df)

输出:

IMG1.tif          IMG2.tif
0    [100, 192, 61]    [100, 207, 68]
1    [299, 208, 62]    [299, 192, 44]

三、迭代操作的便捷方式

  • 长格式迭代:

    for _, row in long_df.iterrows():
        x, y, rgb = row['x'], row['y'], row['z']
        # 执行自定义操作,如打印或计算
        print(f"图像:{row['image_name']}, x:{x}, y:{y}, RGB:{rgb}")
    
  • 原格式迭代:

    for col_name, col_data in df.items():
        for idx, coords in col_data.items():
            x, y, rgb = coords[0], coords[1], coords[2]
            print(f"图像:{col_name}, 索引:{idx}, x:{x}, y:{y}, RGB:{rgb}")
    

内容的提问来源于stack exchange,提问作者mariogarcc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:45:48