Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export list of arrays into csv in Python?

I have this list in Python:

[array([1, 2, 3]), array([3., 4., 5., 6., 7.]), array([7, 8])]

and I would like to export this to csv to look like this - each array on new line...

1, 2, 3

3., 4., 5., 6., 7.

7, 8

Each array has a different length.

I tried to use numpy.savetxt, numpy.vstack but these different lengths give me problems.

Can anyone help?

like image 474
gugatr0n1c Avatar asked Dec 21 '14 14:12

gugatr0n1c


2 Answers

You can also use:

import csv
import numpy as np
b = open('output.csv', 'w')
a = csv.writer(b)
data = [np.array([1, 2, 3]), np.array([3., 4., 5., 6., 7.]), np.array([7, 8])]
a.writerows(data)
b.close()
like image 116
Ujjwal Avatar answered Oct 11 '22 12:10

Ujjwal


Pandas module is particularly good for working with data that has missing values:

import pandas as pd

arr = [[1, 2, 3], [3, 4], [5, 6, 7, 8]]
df = pd.DataFrame(arr)
print(df.to_csv(index=False, header=False))

Output:

'1,2,3.0,\n3,4,,\n5,6,7.0,8.0\n'
like image 39
Pavel Ryvintsev Avatar answered Oct 11 '22 12:10

Pavel Ryvintsev