CSV的2D列表-按列

时间:2019-05-07 14:37:16

标签: python list csv

我想将2D列表的内容导出到csv文件中。

子列表的大小可以不同。例如,2D列表可以是:

  

a = [['a','b','c','d'],['e','f'],['g'],[],['h','i ']]

我希望我的csv像这样存储数据-“按列”:

a,e,g, ,h
b,f, , ,i
c
d

我是否必须添加一些空格以使每个子列表具有相同的大小?还是有另一种方法?

谢谢您的帮助

4 个答案:

答案 0 :(得分:3)

您可以使用itertools.zip_longest

import itertools, csv
a = [ ['a','b','c','d'], ['e','f'], ['g'], [], ['h','i'] ]
with open('filename.csv', 'w') as f:
  write = csv.writer(f)
  write.writerows(list(itertools.zip_longest(*a, fillvalue=''))) 

输出:

a,e,g,,h
b,f,,,i
c,,,,
d,,,,

答案 1 :(得分:0)

可以使用熊猫和转置功能(T)

import pandas as pd
pd.DataFrame(a).T.to_csv('test.csv')

结果: (test.csv)

 ,0,1,2,3,4
0,a,e,g,,h
1,b,f,,,i
2,c,,,,
3,d,,,,

答案 2 :(得分:0)

import itertools
import pandas as pd

首先使用嵌套数组创建一个数据框:

a = ['a','b','c','d']
b = ['e','f']
c = ['g']
d = []
e = ['h','i'] 

nest = [a,b,c,d,e]

df = pd.DataFrame((_ for _ in itertools.zip_longest(*nest)), columns=['a', 'b', 'c', 'd', 'e'])

那样:

    a   b       c       d       e
0   a   e       g       None    h
1   b   f       None    None    i
2   c   None    None    None    None
3   d   None    None    None    None

然后使用熊猫存储它:

df.to_csv('filename.csv', index=False)

答案 3 :(得分:0)

我们在这里要完成三个任务:填充子列表,使它们都具有相同的长度,转置并写入csv。 遗憾的是,Python没有内置的填充函数,但是它可以相对轻松地完成,我会按照以下方式进行 (以下代码旨在提供OP中要求的结果):

a = [['a','b','c','d'],['e','f'],['g'],[],['h','i']]
ml = max([len(i) for i in a]) #number of elements of longest sublist
a = [(i+[' ']*ml)[:ml] for i in a] #adding ' ' for sublist shorter than longest
a = list(zip(*a)) #transpose
a = [','.join(i) for i in a] #create list of lines to be written
a = [i.rstrip(', ') for i in a] #jettison spaces if not followed by value
a = '\n'.join(a) #create string to be written to file
with open('myfile.csv','w') as f: f.write(a)

myfile.csv的内容:

a,e,g, ,h
b,f, , ,i
c
d