我正在使用1d numpy数组,首先做一些数学运算,然后将所有内容保存到一个csv文件中。数据集的长度通常不同,我无法将它们放在一起。这是我能想到的最好的方法,但一定有更优雅的方法。在
import numpy as np
import pandas as pd
import os
array1 = np.linspace(1,20,10)
array2 = np.linspace(12,230,10)
array3 = np.linspace(7,82,20)
array4 = np.linspace(6,55,20)
output1 = np.column_stack((array1.flatten(),array2.flatten())) #saving first array set to file
np.savetxt("tempfile1.csv", output1, delimiter=',')
output2 = np.column_stack((array3.flatten(),array4.flatten())) # doing it again second array
np.savetxt("tempfile2.csv", output2, delimiter=',')
a = pd.read_csv('tempfile1.csv') # use pandas to read both files
b = pd.read_csv("tempfile2.csv")
merged = b.join(a, rsuffix='*') # merge with panda for single file
os.remove('tempfile1.csv')
os.remove("tempfile2.csv") # delete temp files
merged.to_csv('savefile.csv', index=False) # save merged file
您只需使用
concat
并传递paramaxis=1
,将数组追加为列:然后你可以像平常一样把这个写出来
^{pr2}$使用}的解决方案非常简洁:
numpy.savetxt
可能会找到一个不错的解决方案,而且可能还有一个比您的更简单的pandas
解决方案,但是在本例中,使用标准库csv
和{相关问题 更多 >
编程相关推荐