Eric Kim
Eric Kim

Reputation: 2696

python - sort csv files by columns, while preserving the header

I imported the csv into python, and now I have a nested list that looks like this.

data = [['header1,'header2','header3'...], [1,2,3...], [a,b,c...] ]

So the first line is the header row, and the rest are the actual data. I want to sort the data using the following code:

data = sorted(data, key = lambda x: x[1]) #-> sorts data by the 2nd header

But when I do this, the code sorts the header row too, and my header is at the middle of somewhere in my data. How can I preserve my header in the first row, while sorting the rest? I've seen some code that does this by using operator.itemgetter(), but I don't want to do this way

Upvotes: 1

Views: 3874

Answers (2)

Mark
Mark

Reputation: 92461

You can sort a slice of the array like:

data = [['header1','header2','header3'], 
        [1, 2, 3], 
        [2, 3, 4], 
        [5, 6, 7], 
        [3, 4, 5],
        [7, 8, 9], 
        [6, 3, 4] 
]

data[1:] = sorted(data[1:], key = lambda x: x[0])

This takes everything from the first element on,sorts it, and reassigns it to the same slice of the array.

data now is:

 [['header1', 'header2', 'header3'], 
 [1, 2, 3], 
 [2, 3, 4], 
 [3, 4, 5], 
 [5, 6, 7], 
 [6, 3, 4], 
 [7, 8, 9]
 ]

Upvotes: 2

flashyo
flashyo

Reputation: 1

sorted(data[1:], key=lambda x: x[1])

Upvotes: 0

Related Questions