[英]How to write a csv from a numpy.ndarray?
data = [[1 2 3 4][5 6 7 8][9 10 11 12]] 数据= [[1 2 3 4] [5 6 7 8] [9 10 11 12]]
The object I receive has this structure. 我收到的对象具有这种结构。 The numbers in each sub-array aren't separated
每个子数组中的数字不分开
I've tried to convert into a list and then split it but it writes separated rows 我试图转换为列表,然后将其拆分,但它写了分开的行
simMatrix = open(ficheroDestino, 'w', newline='') with simMatrix: writer = csv.writer(simMatrix,delimiter=',') for x in range (0,len(data)): result = data[x].tolist() writer.writerow(result) simMatrix = open(ficheroDestino,'w',newline ='')与simMatrix:writer = csv.writer(simMatrix,delimiter =',')对于范围(0,len(data))中的x:结果= data [x ] .tolist()writer.writerow(结果)
Other code: 其他代码:
simMatrix = open(ficheroDestino, 'w',newline='')
with simMatrix:
writer = csv.writer(simMatrix,delimiter=',')
for x in range (0,len(data)):
result = data[x].tolist()
result2 = ' '.join(str(e) for e in datos)
result3 = datos2.split(" ")
writer.writerow(result3)
I expect the output of my csv as: 1 2 3 4 我希望我的csv输出为:1 2 3 4
5 6 7 8 5 6 7 8
8 10 11 12 8 10 11 12
each number in a different column and row 每个数字在不同的列和行中
I would use Pandas DataFrame to_csv method. 我将使用Pandas DataFrame to_csv方法。 Following is a sample
以下是样本
import numpy as np
import pandas as pd
data = [["1 2 3 4"], ["5 6 7 8"], ["9 10 11 12"]]
pd.DataFrame(np.array([str(i).replace("['", "").replace("']", "").split(" ") for i in data])).to_csv("file.csv")
How about this. 这个怎么样。
import pandas as pd
data = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
datas = pd.DataFrame(data)
print(datas)
datas.to_csv('./test.csv',index=False)
You can just try numpy.savetxt()
, example code is as below: 您可以尝试
numpy.savetxt()
,示例代码如下:
import numpy as np
data = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]).astype(int)
np.savetxt('test.csv', data, fmt='%d', delimiter=' ')
The .csv file will be like: .csv文件将类似于:
1 2 3 4
5 6 7 8
9 10 11 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.