首页 > 解决方案 > 替换特定列值

问题描述

我想遍历数据集并用一个相同的 [value] 替换特定列的值 在此处输入图像描述

整个数据集有 91164 行。这里的情况我需要用vec_red, vec_greem,vec_blue替换new_data

new_data的形状(91164,)和出现次数等于我的数据框的索引。例如最后一项是

在此处输入图像描述

1需要是val_red, val_blue,中的值val_green。所以我想遍历整个数据框并将列中的值从 3 替换为 5。

我所拥有的是:

label_idx = 0
for i in range(321):
    for j in range(284):
      (sth here)   = new_data[label_idx]
        label_idx += 1

这里的情况是我在过滤后更新我的像素值。谢谢你。

91164 的形状是乘法 321 * 284 的结果。这些是我在 RGB 图像中的像素值。

标签: pythonpandasdataframe

解决方案


循环遍历数据帧的行是一种代码异味。如果 3 列必须接收相同的值,您可以在一个操作中完成:

df[['vec_red', 'vec_green', 'vec_blue']] = np.transpose(
    np.array([new_data, new_data, new_data]))

演示:

np.random.seed(0)

nx = 284
ny = 321
df = pd.DataFrame({'x_indices': [i for j in range(ny) for i in range(nx)],
                   'y_indices': [j for j in range(ny) for i in range(nx)],
                   'vec_red': np.random.randint(0, 256, nx * ny),
                   'vec_green': np.random.randint(0, 256, nx * ny),
                   'vec_blue': np.random.randint(0, 256, nx * ny)
                   })

new_data = np.random.randint(0, 256, nx * ny)
print(df)
print(new_data)
df[['vec_red', 'vec_green', 'vec_blue']] = np.transpose(
    np.array([new_data, new_data, new_data]))
print(df)

它按预期给出:

       x_indices  y_indices  vec_red  vec_green  vec_blue
0              0          0      172        167       100
1              1          0       47         92       124
2              2          0      117         65       174
3              3          0      192        249        72
4              4          0       67        108       144
...          ...        ...      ...        ...       ...
91159        279        320       16        162        42
91160        280        320      142        169       145
91161        281        320      225         81       143
91162        282        320      106         93        68
91163        283        320       85         65       130

[91164 rows x 5 columns]
[ 32  48 245 ...  26  66  58]
       x_indices  y_indices  vec_red  vec_green  vec_blue
0              0          0       32         32        32
1              1          0       48         48        48
2              2          0      245        245       245
3              3          0        6          6         6
4              4          0      178        178       178
...          ...        ...      ...        ...       ...
91159        279        320       27         27        27
91160        280        320      118        118       118
91161        281        320       26         26        26
91162        282        320       66         66        66
91163        283        320       58         58        58

[91164 rows x 5 columns]

推荐阅读