Express a list of multiple lines in a single column

Asked 2 years ago, Updated 2 years ago, 14 views

What method should I use to solve the list saved like the image above like the image below?

python

2022-09-20 17:45

1 Answers

import csv
from collections import defaultdict
import itertools as it

with open('input.csv', 'r') as rf, open('output.csv', 'w') as wf:
    csv_reader = csv.DictReader(rf, delimiter=',')
    result = defaultdict(list)
    for row in [{key:value[1:-1].split()} for line in csv_reader for key, value in line.items()]:
        for key, value in row.items():
            result[key].extend(value)
    csv_writer = csv.writer(wf)
    csv_writer.writerow(result.keys())
    csv_writer.writerows(it.zip_longest(*result.values()))
import pandas as pd
import numpy as np

df = pd.read_csv('input.csv', converters={'col1':lambda line:line[1:-1].split(), 'col2':lambda line:line[1:-1].split()})
pd.DataFrame.from_dict({'col1': np.concatenate(df['col1'].values), 'col2':np.concatenate(df['col2'].values)}, orient='index').transpose().to_csv('output.csv', index=False)


2022-09-20 17:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.