Home > Blockchain >  Write multiple lists to different columns in a single cell in CSV
Write multiple lists to different columns in a single cell in CSV

Time:07-13

I have multiple lists and I want to write all those lists under different column names; the list written should be in single-cell only.

columns = [c1, c2, c3]

list1 = ['a', 'b', 'c', 'd']

list2 = [1,2,3,4,5,6]

list3 = ['h', 'j', 'm', 'q', 'w']

Required output:

c1                     c2                   c3

CodePudding user response:

Another version, pass columns= parameter and list of rows into a DataFrame constructor:

df = pd.DataFrame([[list1, list2, list3]], columns=columns)
print(df)

Prints:

             c1                  c2               c3
0  [a, b, c, d]  [1, 2, 3, 4, 5, 6]  [h, j, m, q, w]

CodePudding user response:

You can append each list to a key with the name of columns and then create pandas.DataFrame.

from collections import defaultdict
import pandas as pd

dct = defaultdict(list)
for idx, ls in enumerate([list1, list2, list3]):
    dct[columns[idx%len(columns)]].append(ls) # why `%len(columns)`? see second part
print(dct)

df = pd.DataFrame(dct)
print(df)

Output:

{'c1': [['a', 'b', 'c', 'd']], 'c2': [[1, 2, 3, 4, 5, 6]], 'c3': [['h', 'j', 'm', 'q', 'w']]}

             c1                  c2               c3
0  [a, b, c, d]  [1, 2, 3, 4, 5, 6]  [h, j, m, q, w]

You can add multiple lists to each column.

dct = defaultdict(list)
for idx, ls in enumerate([list1, list2, list3, list1, list2, list3]):
    dct[columns[idx%len(columns)]].append(ls)

df = pd.DataFrame(dct)
print(df)

Output:

             c1                  c2               c3
0  [a, b, c, d]  [1, 2, 3, 4, 5, 6]  [h, j, m, q, w]
1  [a, b, c, d]  [1, 2, 3, 4, 5, 6]  [h, j, m, q, w]
  • Related