I am trying to write a python code that does the following. Can someone help? Thank you!
Read each row in a csv file (file1), transpose it, and stack it into a single column in a new csv file (file2). File1 has data in 6 columns and 90 rows: please click here for an image
CodePudding user response:
I'd first convert the csv to a list of lists -
import csv
with open(InputFile, 'r') as csvFile:
list_of_lists = []
reader = csv.reader(csvFile)
for row_num, row in enumerate(reader):
list_of_lists.append(row)
And then use this to re-arrange the elements. For example, if your list looked like -
list_of_lists = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
result = []
for i in list_of_lists:
for j in i:
result.append(j)
print(result)
# Output:
# [1, 1, 1, 2, 2, 2, 3, 3, 3]
Just adding a note that its not what transpose means. Transpose would convert rows to columns and columns to rows
CodePudding user response:
import csv
with open('input.csv') as infile:
csvreader = csv.reader(infile, delimiter=',') # select your csv's delimiter
out = []
for row in csvreader:
out.extend(row)
Now all your rows have been joined in 1 list. Now you can save it as a single column in a new csv file.