data = [[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)
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
5 6 7 8
8 10 11 12
each number in a different column and row
I would use Pandas DataFrame to_csv method. 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:
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:
1 2 3 4
5 6 7 8
9 10 11 12
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.