使用
numpy
阵列:
import numpy as np
Data = np.arange(25).reshape((5,5))
#Data
#array([[ 0, 1, 2, 3, 4],
# [ 5, 6, 7, 8, 9],
# [10, 11, 12, 13, 14],
# [15, 16, 17, 18, 19],
# [20, 21, 22, 23, 24]])
switch = np.loadtxt('./test.txt', comment='#')
switch
现在包含6行,其中第一行是旧数字,第二行是新数字。通过循环行数,我们可以更改像素值:
for i in range(switch.shape[0]):
Data[Data == switch[i, 0]] = switch[i, 1]
#Data
#array([[ 0, 23, 2, 11, 11],
# [15, 6, 7, 8, 9],
# [10, 11, 12, 13, 14],
# [15, 16, 17, 18, 19],
# [20, 21, 22, 23, 24]])
test.txt文件:
#old new
0 0
1 23
2 2
3 11
4 11
5 15
编辑:
如果您的数据是在一个.csv文件中,就像在您更新的问题中一样,只需调整
loadtxt
呼叫:
switch = np.loadtxt('./text.txt', usecols=(1,2), delimiter=',')
这样我们就忽略了第一列(numpy不能处理混合类型的数组(float和string))并且将分隔符从空白改为逗号。
注意:文件扩展名在这里并不重要,它可以是.txt或.csv或任何其他文件。只有文件内容才是重要的。