根据 DateTime 字段对 Pandas 数据框进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38376938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:35:19  来源:igfitidea点击:

Sort a pandas dataframe based on DateTime field

sortingpandasdataframe

提问by user3447653

I am trying to sort a dataframe based on DateTime field which is of datatype datetime64[ns].

我正在尝试根据数据类型为 datetime64[ns] 的 DateTime 字段对数据框进行排序。

My dataframe looks like this:

我的数据框如下所示:

Name    DateTime1
P38     NaT
P62     2016-07-13 16:03:32.771
P59     2016-06-23 14:23:42.461
P07     NaT
P16     2016-06-23 14:02:06.237
P06     2016-07-13 16:03:52.570
P106    2016-07-13 19:56:22.676

When I sort it using DateTime field,

当我使用 DateTime 字段对其进行排序时,

df.sort_values(by='DateTime1',ascending=True)

I do not get the desired result.

我没有得到想要的结果。

Output:

输出:

Name    DateTime1
P16     2016-06-23 14:02:06.237
P59     2016-06-23 14:23:42.461
P62     2016-07-13 16:03:32.771
P06     2016-07-13 16:03:52.570
P106    2016-07-13 19:56:22.676
P38     NaT
P07     NaT

回答by ctrl-alt-delete

Your code should work?

你的代码应该可以工作?

Try

尝试

df = df.sort_values(by='DateTime1',ascending=True)
df

You could create an index

你可以创建一个索引

df.set_index('DateTime1', drop=True, append=False, inplace=True, verify_integrity=False)
df = df.sort_index()

回答by Newb

Did you try assigning back to the data frame?

您是否尝试分配回数据框?

df = df.sort_values(by='DateTime1',ascending=True)
df

This df should have sorted values

这个 df 应该有排序的值

回答by Benny Louisot

you didn't overwrite youre df, like:

你没有覆盖你的 df,比如:

df = df.sort_values(by='DateTime1',ascending=True)