Reputation: 12381
The aim is to merge four lists result
, trainAcc
, crossAcc
and testAcc
, each of the same length column wise and store the resulting matrix as a CSV file along with necessary headings.
The following is my working code to do this.
acc = np.concatenate((np.array(result,ndmin=2).T,
np.array(trainAcc, ndmin=2).T,
np.array(crossAcc, ndmin=2).T,
np.array(testAcc, ndmin=2).T), axis=1)
acc = np.concatenate((np.array(["Classifier","Train Accuracy", "CV Accuracy", "Test Accuracy"], ndmin=2), acc), axis=0)
with open("bestClassifier.csv", 'wb') as f:
csv.writer(f).writerows(acc)
As you can see, the code is not so aesthetically pleasing for a task so simple. All lists have to be converted to two dimensional arrays and transposed in order to be merged column-wise.
Is there a simpler way to do this task with or without NumPy?
Upvotes: 0
Views: 1166
Reputation: 25083
Why not
acc = np.array((result, trainAcc, crossAcc, testAcc)).T
testing it
In [14]: np.array(([1,2,3,4,5],[10,20,30,40,50])).T
Out[14]:
array([[ 1, 10],
[ 2, 20],
[ 3, 30],
[ 4, 40],
[ 5, 50]])
What about the output?
In [25]: acc = np.array(([1,2,3,4,5],[10,20,30,40,50])).T
In [26]: with open('pip.csv','w') as f:
....: writer = csv.writer(f)
....: writer.writerow(['Units', 'Tens'])
....: writer.writerows(acc)
In [27]: !cat pip.csv
Units,Tens
1,10
2,20
3,30
4,40
5,50
Upvotes: 2
Reputation: 7000
To merge lists:
a = [1, 2, 3, 4]
b = [10, 20, 30, 40]
c = [100, 200, 300, 400]
zipped = zip (a, b, c)
print (zipped)
# [(1, 10, 100), (2, 20, 200), (3, 30, 300), (4, 40 400)]
Upvotes: 2