Python csv writer在单行中组合两列

时间:2018-05-11 01:33:15

标签: python csv numpy

我正在尝试在csv的第一列中编写img_id(单值),在csv文件的其余列中编写图像特征数组(f_descriptor_T)。 我写了以下代码:

path=/home/dir
listing = os.listdir(path)    

for file in listing:
    path_img_ext = os.path.join(path, file) #combine filename and extension
    data_read = feature_io.ReadFromFile(path_img_ext) #read single features of single image in each iteration 

    base=os.path.basename(file) #Extract image_id from its name
    os.path.splitext(file)
    img_id = os.path.splitext(base)[0]

    f_descriptor = data_read[2] #Extract particular array, from multiple arrays of features 

    feature_flat=f_descriptor.flatten() #Make flat array

    f_descriptor_T = np.array(feature_flat).T #Transpose feature array to convert col data to row form. 

    with open("output_0.csv", "a") as f:
        writer = csv.writer(f)
        writer.writerow([img_id])
        writer.writerow(f_descriptor_T)

不幸的是,输出在一行上显示img_id,在第二行显示f_descriptor_T,每次循环迭代,如下面的屏幕截图所示:Output

但我想将(变量和数组)组合在一起。

注意:我已经尝试过zip和concatenate来组合两者,但都失败了。

所需的输出应该是这样的:Desired Output不需要打印列标题,只需要在单行中打印img_id和f_descriptor_T数组。

1 个答案:

答案 0 :(得分:0)

尝试重现您的csv文件

In [131]: arr = np.arange(10) # a flat array
In [132]: arr = np.array(arr).T
In [133]: arr
Out[133]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

我从平面文件开始,仍然有一个平面文件(1d数组上的.T什么都不做)

In [135]: with open('out.csv','a') as f:
     ...:     writer = csv.writer(f)
     ...:     writer.writerow(['id'])
     ...:     writer.writerow(arr.T)
     ...:     
In [136]: cat out.csv
id
0,1,2,3,4,5,6,7,8,9

每次调用writerow都会写一行,顾名思义。

但是使用savetxt我可以轻松地在整齐的列和行中编写一个二维数组:

In [137]: np.savetxt('out.csv', arr.reshape(5,2), delimiter=',')
In [138]: cat out.csv
0.000000000000000000e+00,1.000000000000000000e+00
2.000000000000000000e+00,3.000000000000000000e+00
4.000000000000000000e+00,5.000000000000000000e+00
6.000000000000000000e+00,7.000000000000000000e+00
8.000000000000000000e+00,9.000000000000000000e+00
In [139]: np.savetxt('out.csv', arr.reshape(5,2), delimiter=',', fmt='%5d')
In [140]: cat out.csv
    0,    1
    2,    3
    4,    5
    6,    7
    8,    9

混合文字和数字有点棘手。

我只需将两个变量放在列表中即可将其写入一行:

In [143]: with open('out.csv','w') as f:
     ...:     writer = csv.writer(f)
     ...:     writer.writerow(['id', arr])
     ...: 
     ...:     
In [144]: cat out.csv
id,[0 1 2 3 4 5 6 7 8 9]

实际上已经完成了:

f.writeline('%s,%s'%(id, arr))

即将列表格式化为字符串并写入。