[英]Sorting rows in csv file using Python Pandas
I have a quick question regarding sorting rows in a csv files using Pandas. 我有一个关于使用熊猫对csv文件中的行进行排序的快速问题。 The csv file which I have has the data that looks like:
我拥有的csv文件具有如下数据:
quarter week Value
5 1 200
3 2 100
2 1 50
2 2 125
4 2 175
2 3 195
3 1 10
5 2 190
I need to sort in following way: sort the quarter and the corresponding weeks. 我需要按以下方式进行排序:对季度和相应的星期进行排序。 So the output should look like following:
因此输出应如下所示:
quarter week Value
2 1 50
2 2 125
2 3 195
3 1 10
3 2 100
4 2 175
5 1 200
5 2 190
My attempt: 我的尝试:
df = df.sort('quarter', 'week')
But this does not produce the correct result. 但这不会产生正确的结果。 Any help/suggestions?
任何帮助/建议吗?
Thanks! 谢谢!
Note :
sort
has been deprecated in favour ofsort_values
, which you should use in Pandas 0.17+.注 :
sort
已赞成被否决sort_values
,你应该在熊猫使用0.17+。
Typing help(df.sort)
gives: 键入
help(df.sort)
会给出:
sort(self, columns=None, column=None, axis=0, ascending=True, inplace=False) method of pandas.core.frame.DataFrame instance
Sort DataFrame either by labels (along either axis) or by the values in
column(s)
Parameters
----------
columns : object
Column name(s) in frame. Accepts a column name or a list or tuple
for a nested sort.
[...]
Examples
--------
>>> result = df.sort(['A', 'B'], ascending=[1, 0])
[...]
and so you pass the columns you want to sort as a list: 因此,您将要排序的列作为列表传递:
>>> df
quarter week Value
0 5 1 200
1 3 2 100
2 2 1 50
3 2 2 125
4 4 2 175
5 2 3 195
6 3 1 10
7 5 2 190
>>> df.sort(["quarter", "week"])
quarter week Value
2 2 1 50
3 2 2 125
5 2 3 195
6 3 1 10
1 3 2 100
4 4 2 175
0 5 1 200
7 5 2 190
New answer, as of 14 March 2019 截至2019年3月14日的新答案
df.sort_values(by=["COLUMN"], ascending=False)
This returns a new sorted data frame, doesn't update the original one. 这将返回一个新的排序数据框,而不更新原始数据框。
Note: You can change the ascending parameter according to your needs, without passing it, it will default to ascending=True
注意:您可以根据需要更改升序参数,而无需将其传递,它将默认为
ascending=True
DataFrame
对象没有属性sort
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.