Home > front end >  save values in separate columns
save values in separate columns

Time:03-13

I have a CSV dataset that one of its labels is like this picture.

enter image description here

How could I save these zeros and ones in separate columns?

I mean it should be like this picture:

enter image description here

CodePudding user response:

In theory, the output you'd want is something like:

label
0,0,0,0,1
0,0,1,0,0
0,0,0,0,1

Assuming your CSV data is in a list csvdata like so:

csvdata = [[0,0,0,0,1],[0,0,1,0,0]] # ...

You would want to do something like this:

with open("csv.csv", "w") as csv:
    csv.write("label1,label2,label3,label4,label5")
    for row in csvdata: # Get all the rows in our CSV
        is_first = True # make sure we don't write a comma on the first cell.
        for cell in row: # Now get each of the cells
            if not is_first: # Make sure this isn't our first cell
                csv.write(",") # Write a comma after the last line if it's not.
            csv.write(cell) # Write cell data
            is_first = False # Tell the program this isn't our first cell

Let's break down this code:

On the first line, we open our CSV file in write mode. Then we write our header. Line endings are handled for us.

Now we iterate over each of our rows, and make a flag to tell the program this is the first cell.

Now, within that row, we iterate over our cells

If it's not the first cell in that row, write a comma to close the previous cell.

Then, make sure the program knows this isn't our first run on this row.

  • Related