Python 如何将numpy数组转换为csv
如何将NumPy数组转换为CSV文件。 我在下面提到了代码:Python 如何将numpy数组转换为csv,python,python-3.x,list,csv,export-to-csv,Python,Python 3.x,List,Csv,Export To Csv,如何将NumPy数组转换为CSV文件。 我在下面提到了代码: array_of_nparray = [[[1,2,3,4]],[[5,6,7,8]],[[9,10,11,12]]] header = ["a","b","c","d"] 要使用csv格式,请执行以下操作: a | b | c | d| 1 | 2 | 3 | 4| 5 | 6 | 7 | 8| 9 | 10 | 11 | 12| 我试着用它来做 w
array_of_nparray = [[[1,2,3,4]],[[5,6,7,8]],[[9,10,11,12]]]
header = ["a","b","c","d"]
要使用csv格式,请执行以下操作:
a | b | c | d|
1 | 2 | 3 | 4|
5 | 6 | 7 | 8|
9 | 10 | 11 | 12|
我试着用它来做
with open("abc.csv","w") as f:
m = csv.writer(f)
m.writer(header)
m.writerow(array_of_nparray)
But was unsuccessful because it printed all the NumPy arrays in the first column
Can anyone please help
您可以使用熊猫:
您也可以使用简单的字符串格式: 数组的数组=[[1,2,3,4],[[5,6,7,8],[[9,10,11,12]] 标题=[a、b、c、d] 使用openabc.csv,w作为f: f、 写入+','.joinheader+'\n' 对于数组的数组中的行: f、 写入“,”。在第[0]行中加入[stri for i]+“\n”
但是,必须根据不同的情况进行调整。将数组转换为pandas数据帧,然后将其保存为CSV格式
import pandas as pd
array_of_nparray = [[[1,2,3,4]],[[5,6,7,8]],[[9,10,11,12]]]
header = ["a","b","c","d"]
df = pd.DataFrame(np.array(array_of_nparray).reshape((3,4)), columns=header)
df.to_csv("data.csv", index=False)
通过示例,我得到了以下解决方案:
import numpy as np
array_of_nparray = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
header = ' a, b, c, d'
np.savetxt('2darray.csv', array_of_nparray, delimiter=',', header=header ,fmt='%d', comments='')
这不是一个numpy数组数组:数组\u of \u nparray=[[[1,2,3,4],[[5,6,7,8],[[9,10,11,12]],它是一个三维嵌套列表。
import numpy as np
array_of_nparray = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
header = ' a, b, c, d'
np.savetxt('2darray.csv', array_of_nparray, delimiter=',', header=header ,fmt='%d', comments='')