How can I transform csv data in python

Question:

I have a csv file that I want to transform. Currently the data looks like this in the csv file

115776 1142 1523 20197 20394 3421 1284 9572 19682 

but I want it to look like this

115776 1142
115776 1523
115776 20197
115776 20394
115776 3421 

…..

any idea on how to achieve this?

I currently wrote a function to get it and it gets it like this

for row in read_csv(testfile, "Recipes_RecipeId Recipes_Ingredients_0_IngredientID Recipes_Ingredients_1_IngredientID Recipes_Ingredients_2_IngredientID Recipes_Ingredients_3_IngredientID Recipes_Ingredients_4_IngredientID Recipes_Ingredients_5_IngredientID Recipes_Ingredients_6_IngredientID Recipes_Ingredients_7_IngredientID Recipes_Ingredients_8_IngredientID".split()):
    with open('recipeIngredientID.csv', 'a') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(row)

is there any better way to do it where it prints it out I want it?

Asked By: Abby

||

Answers:

Read the csv into a python list: Python import csv to list

And then simply loop over the list with repeating the first index:

test = [115776, 1142, 1523, 20197, 20394, 3421, 1284, 9572, 19682]

for i in test[1:]:
     print test[0], i
Answered By: bjpreisler

For smaller csv you can load csv to array of arrays, make empty rotated array and copy data. Like this…

head -n 10 vf.txt | python -c "
import sys
import csv
reader=csv.reader(sys.stdin)
mx = []
for row in reader:
    mx.append(row)

cols = len(mx[0])
rows = len(mx)
outp = [[None for e in range(0,rows) ] for i in range(0,cols)]
for r in range(0, rows):
    for c in range(0,cols):
        outp[c][r] = mx [r][c]

writer = csv.writer(sys.stdout)
for r in outp:
    writer.writerow(r)
"""
Answered By: Jelen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.