2D list to csv - by column

廉价感情. 提交于 2021-01-27 20:00:10

问题


I'd like to export the content of a 2D-list into a csv file.

The size of the sublists can be different. For example, the 2D-list can be something like :

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

I want my csv to store the data like this - "by column" :

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

Do I have to add some blank spaces to get the same size for each sublist ? Or is there another way to do so ?

Thank you for your help


回答1:


You can use 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=''))) 

Output:

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



回答2:


It can be done using pandas and transpose function (T)

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

Result: (test.csv)

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



回答3:


import itertools
import pandas as pd

First create a dataframe using a nested array:

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'])

like that:

    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

and then store it using pandas:

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



回答4:


We have three task to do here: fill sublist so all have same length, transpose, write to csv. Sadly Python has not built-in function for filling, however it can be done relatively easily, I would do it following way (following code is intended to give result as requested in 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)

Content of myfile.csv:

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


来源:https://stackoverflow.com/questions/56025046/2d-list-to-csv-by-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!