从 CSV 文件读取和写入 NP 数组时出现问题



这是我之前发布的问题的(不同(延续。 我以前的 csv 文件格式不正确@The Puternerd 善意地建议我在将 2d 数组写入文件之前将其展平。

所以这是我所拥有的:

output = open(CSVFilepath,"w")
csvwriter=csv.writer(output, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for imagePath in glob.glob(MaskImagePath):
...
#myDescriptor is the 2d np array with varying rows and fixed columns (60)
myrow=[imageID,myDescriptor.shape[0],myDescriptor.flatten()]

这是我的csv文件现在的样子:

000000216739.jpg,224,[0. 0. 0. ... 0. 1. 2.]
000000001268.jpg,173,[0. 0. 0. ... 0. 1. 0.]
000000166259.jpg,195,[0. 0. 0. ... 0. 0. 2.]
000000368900.jpg,226,[0. 0. 0. ... 1. 1. 1.]

但是当我尝试用以下方法检索第三项时:

with open(CSVFilepath,'r') as fin:
reader = csv.reader(fin,delimiter=',')
for row in reader:
print(row[2])
print(type(row[2]))
print(np.array(list(row[2])))

它返回:

[0. 0. 0. ... 1. 3. 2.]
<class 'str'>
['[' '0' '.' ' ' '0' '.' ' ' '0' '.' ' ' '.' '.' '.' ' ' '1' '.' ' ' '3' '.' ' ' '2' '.' ']']

这是否意味着我没有正确保存值?任何建议将不胜感激!!

**********更新**************

阅读下面的@Navneeth说明,现在我有这个代码:

with open(CSVFilepath,'r') as fin:
reader = csv.reader(fin,delimiter=',')
for row in reader:
print(row[2])
print(type(row[2]))
a = row[2].replace("n","")
print(a)
print(np.fromstring(a[1:-1], dtype=float, sep=" "))

但它打印:

[0. 0. 0. ... 1. 2. 0.]
<class 'str'>
[0. 0. 0. ... 1. 2. 0.]
[0. 0. 0.]
[0. 0. 0. ... 1. 3. 2.]
<class 'str'>
[0. 0. 0. ... 1. 3. 2.]
[0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
<class 'str'>
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0.]

CSV 文件的编码本身没有问题。但是,CSVReader无法识别您正在尝试从第三列读取 numpy 数组,因此它只返回该 numpy 数组的字符串表示形式。

你的第三个 print 语句给你这种奇怪的格式的原因是,在字符串上使用numpy.array会导致 numpy 将其解释为单个字符的数组(这是很自然的,因为这个函数会将任何可迭代对象分解为其单独的元素,就像你调用list("mystring")一样(。

这是使用numpy.fromstring将字符串解释为 numpy 数组的一种简短方法。

def string_to_numpy(column):
return numpy.fromstring(column[1:-1], dtype=float, sep=" ")

拼接是必需的,因为numpy.fromstring不需要输入中的[]字符。该调用使用单个空格字符作为分隔符,但如果这不够通用,您可以更漂亮并使用正则表达式。

请注意,此处生成的数组是平面的。如果要还原数组的维度,则必须在将维度提取为整数后使用numpy.array.reshape

最新更新