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.
Advertisement
Answer
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)