0

How to split following list to multiple rows (3 rows) and write in to a csv file using python.

holidays = ['2017-01-01', "New Year's Day", 'NSW', '2017-01-02', "New Year's Day (Observed)", 'NSW', '2017-01-26', 'Australia Day', 'NSW', '2017-04-14', 'Good Friday', 'NSW', '2017-04-15', 'Easter Saturday', 'NSW']

Following code write all values to single column in a csv.

Title = ('date', 'name','state')

with open(fileName,"w") as output:
    writer = csv.writer(output,lineterminator='\n')
    for val in lstAll:
        writer.writerow([val])

3 Answers 3

3

A solution using pandas

import pandas as pd

holidays = ['2017-01-01', "New Year's Day", 'NSW', '2017-01-02', "New Year's Day (Observed)", 'NSW', '2017-01-26', 'Australia Day', 'NSW', '2017-04-14', 'Good Friday', 'NSW', '2017-04-15', 'Easter Saturday', 'NSW']
col_titles = ('date', 'name','state')

data = pd.np.array(holidays).reshape((len(holidays) // 3, 3))

pd.DataFrame(data, columns=col_titles).to_csv("holidays.csv", index=False)

Where:

  1. pd.np.array(holidays) converts holidays to a numpy.array
  2. .reshape((len(holidays) // 3, 3)) changes the structure of the array to three "columns"
  3. pd.DataFrame(data, columns=col_titles) creates a pandas.Dataframe from data and col_titles
  4. .to_csv("holidays.csv", index=False) saves the dataframe to a CSV file

Content of holidays.csv:

date,name,state
2017-01-01,New Year's Day,NSW
2017-01-02,New Year's Day (Observed),NSW
2017-01-26,Australia Day,NSW
2017-04-14,Good Friday,NSW
2017-04-15,Easter Saturday,NSW

Note that the index will not be included if you use index=False in to_csv.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use list slicing to process the list in chunks of 3:

with open(fileName, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for i in range(0, len(lst), 3)):
        writer.writerow(lst[i:i+3])

Comments

0

Here's a kind of verbose example that shows how the list interpretation works:

with open('outfile.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    rows = [[holiday, holidays[i+1], holidays[i+2]] for i, holiday in enumerate(holidays) if i % 3 == 0]
    for row in rows:
        writer.writerow(row)

1 Comment

There's no list slicing here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.