0

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?

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
Abby
  • 67
  • 1
  • 11

2 Answers2

0

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
Community
  • 1
  • 1
bjpreisler
  • 118
  • 1
  • 8
0

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)
"""
Jelen
  • 613
  • 5
  • 7