import csv
reader = csv.reader(open("file.csv"))
sortedlist = sorted(reader, key=int(operator.itemgetter(3)))
# 3 or 'n' depending upon which column you want to sort the data
with open("sorted_file.csv", 'wb') as f:
csv.writer(f).writerows(sortedlist)
import pandas as pd
df = pd.read_csv('biostats.csv')
df
Name Sex Age Height (in) Weight (lbs)
0 Alex M 41 74 170
1 Page F 31 67 135
2 Quin M 29 71 176
3 Ruth F 28 65 131
4 Ruth F 59 75 131
5 Quin M 19 55 46
我觉得这应该行得通
排序时只需将键转换为int类型。在
Python令人印象深刻!!在
如果您使用的是pandas library版本>;0.25,则可以使用排序值
df.sort_值(['Name','Sex'],升序=[True,True])
^{pr2}$听起来你想要的是顺序/数字排序,但你得到的是字母排序。字母顺序是1,10,100,2等等,而顺序排序会得到1,2,10,100。在
当从CSV读入数据时,您尝试排序的数据可能是字符串格式的,在调用Python的sort函数之前,您需要将其转换为int。在
可以通过将key=int作为参数传递给sort函数来实现,这将导致它对正在排序的成员调用int()。在
更多信息可以在这里找到:How to sort a list numerically?
相关问题 更多 >
编程相关推荐