Skip to content
Advertisement

manipulating csv file python

i want to rearange a csv file :

from

actual format

JavaScript

to

format desired

JavaScript

i do generate this csv file by searching in a another csv file using:

JavaScript

and

JavaScript

i want the result diffrently as showen above.

Thanks.

got a partiel answer :

JavaScript

and now the result is :

JavaScript

i need to dispatch them on every line

Advertisement

Answer

I don’t know Pandas, but I do know Python’s CSV module:

JavaScript

First, you’ll create output_rows, where you’ll store your new “sub rows” as you make them:

JavaScript

You’ll read the input CSV and capture the header:

JavaScript

Then it’s on to iterating the input rows:

JavaScript

Each row will look something like this:

JavaScript

and you need to be able to expand the columns values, then group the expanded values: all the first items from each column, then all the second items from each column, and so on.

You want to get that row to look something like this:

JavaScript

The way to do that is to split each column, then use Python’s zip() function to interleave the items:

JavaScript

sub_rows now looks like that desired list of lists of strings, from just above.

Now for each sub row, you add the SWA in to create a new output row:

JavaScript

Finally, you write the output rows to a new CSV:

JavaScript

When I put that all together and run it against this input.csv:

JavaScript

I get this output.csv:

JavaScript

If you want to do this in Pandas, take a look at some of the Pandas solutions for this similar problem: How to split a row into two rows in python based on delimiter in Python.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement