如何在Python中将数组列表导出到csv中?

时间:2022-06-23 23:17:12

I have this list in Python:

我在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...

我想把它导出到csv看起来像这样 - 新行上的每个数组......

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.

我尝试使用numpy.savetxt,numpy.vstack,但这些不同的长度给我带来了问题。

Can anyone help?

有人可以帮忙吗?

2 个解决方案

#1


3  

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()

#2


3  

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

Pandas模块特别适合处理缺少值的数据:

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'

#1


3  

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()

#2


3  

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

Pandas模块特别适合处理缺少值的数据:

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'