niub
niub

Reputation: 19

Sort arrays in alphabetical order and numeric order

import csv
num_rows = 0

f_obj = open("Class1.csv", encoding='utf-8-sig')
f = f_obj.read()

for row in open("Class1.csv", encoding='utf-8-sig'):
  num_rows = num_rows + 1

for i in range(1,num_rows):
  f_values = (f.split('\n')[i]).split(",")
  print(f_values)
  #Output:
  
  #['ALEX', '0', '0', '0']
  #['DAVID', '10', '11', '10']
  #['Ben', '10', '10', '10']

sortType = input("1) Sort by Alphabetical Order" "\n" "2) Sort by Total Score" "\n")
if sortType == 1:
  #I want it to output output:
  
  #['ALEX', '0', '0', '0']
  #['Ben', '10', '11', '10']
  #['DAVID', '10', '11', '11']
elif sortType == 2:
  #I want it to output:
  
  #['DAVID', '10', '11', '11']
  #['Ben', '10', '11', '10']
  #['ALEX', '0', '0', '0']

So I have made the code above which fetches data from a .csv file and prints it out. I want to be able to print out the data in alphabetical and numerical order but I am not sure how to go about swapping them around. This is just a sample of data, the real list is about 100 lines long and I want to make sure all of them are sorted correctly in order. enter image description here

Upvotes: 0

Views: 105

Answers (4)

Иван Балван
Иван Балван

Reputation: 598

Assuming that 'Class1.csv' has no header and no special column for row names, and consists of rows separated by newline with values separated by comma, and has no empty values, and everything else, as I hope it is. Try this:

import pandas as pd
df=pd.read_csv('Class1.csv',header=None)

Next... to sort alphabetically:

df=df.sort_values(0) #0 is the column with names
#uncomment the following line to create a new **csv** file:
#df.to_csv('Class_sorted_alpha.csv',header=False,index=False)

Next... to sort numerically:

#create a column with total score
#(df.loc[:,1:] is the numerical part of the column):
df=df.assign(total=df.loc[:,1:].sum(axis=1))
#sort by the 'total' column:
df=df.sort_values('total',ascending=False)
#delete the unnecessary "total" column:
del df['total']
#uncomment the following line to create a new **csv** file:
#df.to_csv('Class_sorted_numerically.csv',header=False,index=False)

Upvotes: 1

Mohammad Tehrani
Mohammad Tehrani

Reputation: 305

You can use default python sort method:

You need to specify the column you want to use as your base to sort inside the x[i] like below:

sortType = input("1) Sort by Alphabetical Order" "\n" "2) Sort by Total Score" "\n")
if sortType == 1:
    f_values.sort(key=lambda x: x[0])
elif sortType == 2:
    f_values.sort(key=lambda x: x[1])

Upvotes: 0

Jib
Jib

Reputation: 1582

You can specify a custom sorting function to accomplish this:

def getname(item):
    return item[0]

def sortByName(item1, item2):
    if getname(item1) < getname(item2):
        return -1
    elif getname(item1) > name(item2):
        return 1
    else:
        return 0

# populate a "super" list which contains all of your sub lists
mlist = []
for i in range(1,num_rows):
    f_values = (f.split('\n')[i]).split(",")
    mlist.append(f_values)

# then sort it out
mlist.sort(key=sortByName)
mlist.sort(key=sortByName, reverse=True)

Edit:

By the way, you can simplify the file reading to this:

# ...

with open("", "r") as f:
    content = f.readlines()

for line in content:
    mlist.append(l.split(","))

print("total rows: {}".format(len(mlist)))

# ...

Upvotes: 0

gog
gog

Reputation: 11347

Start by writing functions that extract a sorting key from a row:

def by_name(row):
   return row[0]

def by_total_score(row):
   return sum(int(x) for x in row[1:])

In the sorting part, simply provide one of these as the key argument to sort:

 if sort_type == 1:
   rows.sort(key=by_name)
 if sort_type == 2:
   rows.sort(key=by_total_score)

Good luck!

Upvotes: 0

Related Questions