PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 26, 2022

[FIXED] How can I transform csv data in python

 August 26, 2022     csv, python, transform     No comments   

Issue

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?


Solution

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
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing