python - 替换特定列值
问题描述
我想遍历数据集并用一个相同的 [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 图像中的像素值。
解决方案
循环遍历数据帧的行是一种代码异味。如果 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]
推荐阅读
- ios - 如何在不以编程方式更改其他单元格的情况下将 UIButton 样式设置为特定的 UITableViewCell?
- python - Pandas:如果满足条件,则在数据框中包含新的时间戳行
- node.js - npm 错误!azure devops 中的代码 ELIFECYCLE 无法使其运行
- qt - 需要 QtWebEngine 32bit dll
- python - 正则表达式搜索 - 在测试器中工作,而不是在 Spyder
- html - Css,固定位置在移动设备上不起作用
- c++ - C++ 结构集无法按元素查找/擦除
- java - WebTest Cient 的 exchange() 编码 url 导致“预期状态:<200> 但原为:<404>”。有什么办法可以阻止它对我的 URL 进行编码
- node.js - 为什么每次部署后我的反应应用程序不清除缓存?
- c# - 将网络模块链接到 msbuild 中的单个文件