从csv字符串加载numpy.ndarray [英] load numpy.ndarray from csv string

查看:303
本文介绍了从csv字符串加载numpy.ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将图像转换为numpy数组并保存到csv文件

I converted images to numpy array and saved to csv file

back_ground = Back_ground()
X = make_test_set('back_ground.csv',back_ground,3500)
Y = back_ground.make_answer()

with open('background.csv','w',newline='') as csvfile:
    fieldnames = ['image','answer']
    writer = csv.DictWriter(csvfile,fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'image': X, 'answer':Y})

make_test_set()make_answer()返回numpy.ndarray

make_test_set() and make_answer() return numpy.ndarray

但是当我想使用这些数据时,就像这样

But when I want to use this data, like this

with open('background.csv','r') as csvfile:
    reader = csv.DictReader(csvfile)
    for number,value in enumerate(reader):
        print(number)
        current_img = value['image']
        print(type(current_img))
        plt.imshow(current_img)
        plt.show()

类型是字符串,所以我不能使用任何numpy函数 如何转换为numpy.ndarray?还是有什么好的方法来保存numpy.ndarray?

type of currnet_img is string so I can't use any numpy functions how can I convert to numpy.ndarray? or are there any good method to save numpy.ndarray?

推荐答案

In [26]: import csv
In [27]: X = np.arange(12).reshape(3,4)
In [28]: Y = np.arange(12)
In [29]: with open('background.csv','w',newline='') as csvfile:
    ...:     fieldnames = ['image','answer']
    ...:     writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
    ...: 
    ...:     writer.writeheader()
    ...:     writer.writerow({'image': X, 'answer':Y})
    ...:     
In [30]: cat background.csv
image,answer
"[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]",[ 0  1  2  3  4  5  6  7  8  9 10 11]

DictWriter编写了2个值的str表示形式,并用多行引号引起来:

The DictWriter has written the str representation of the 2 values, and quoted the multiline one:

In [31]: str(X)
Out[31]: '[[ 0  1  2  3]\n [ 4  5  6  7]\n [ 8  9 10 11]]'

没有将str(X)转换回X的简便方法.

There isn't a convenient way of converting that str(X) back into X.

保存这2个数组的一种好方法是使用savez:

A good way of saving these 2 arrays would be with savez:

In [40]: np.savez('background.npz', image=X, answer=Y)
In [42]: data = np.load('background.npz')
In [43]: list(data.keys())
Out[43]: ['image', 'answer']
In [44]: data['image']
Out[44]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [45]: data['answer']
Out[45]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

这篇关于从csv字符串加载numpy.ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆