简体   繁体   English

如何通过python在excel中按字母顺序对列进行排序?

[英]How to sort a column alphabetically in excel through python?

My task was to create a playlist with the title,artist and length and genre but the titles had to be sorted alphabetically i tried to sort out my song title column but it isnt working at all. 我的任务是创建一个带有标题,艺术家,长度和流派的播放列表,但标题必须按字母顺序排序,我试图对我的歌曲标题列进行排序,但根本不起作用。 Here's my code: 这是我的代码:

Songs list 歌曲清单

songs=open("songs.csv","w")
song_record="song title"+","+"artist"+","+"track length"+","+"genre"
songs.write(str(song_record)+"\n"+"\n")


print("Welcome! Please choose 5 songs per genre")
for i in range (3):
    songtitle=str(input("What is the song called"))
    artists=str(input("Who sung the song ( the main person)"))
    length=str(input("In seconds, how long is the song- 1 min= 60 seconds"))
    genree=str(input("What genre is this song"))
    song_record=songtitle+","+artists+","+length+","+genree
    songs.write(str(song_record)+"\n")
songs.write("\n")
songs.close()

songs=open("songs.csv","a+")
csv1=csv.reader(songs,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
print(sort)
songs.close()

Instead of using csv.reader, use pandas.read_csv and then use sort_values function to sort the values. 代替使用csv.reader,使用pandas.read_csv,然后使用sort_values函数对值进行排序。

import pandas as pd
df=pd.read_csv("songs.csv")
df=df.sort_values(['songtitle'], ascending=[True])

You can set ascending as False if you wish to. 如果愿意,可以将升序设置为False。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM