gpt4 book ai didi

python - 按原始系列索引的时间顺序返回 pandas 日期时间系列

转载 作者:行者123 更新时间:2023-11-28 21:40:29 25 4
gpt4 key购买 nike

我编译了一个 pandas 系列的日期时间如下(下面以系列的一部分为例):

0   2002-02-03
1 1979-01-01
2 2006-12-25
3 2008-07-16
4 2005-05-30

注意:每个cell的dtype是'pandas._libs.tslib.Timestamp'

对于上面的例子,我想按时间顺序对它们进行排名,并按原始系列的索引返回一个系列,如下所示(第二列):

0   1
1 0
2 3
3 4
4 2

我尝试过混合使用 .order()、.sort() 和 .index() 来实现这一点,但到目前为止无济于事。按照原始系列的索引按时间顺序获取一系列日期时间的最简单方法是什么?

谢谢。

最佳答案

您可以使用 Series.rank ,减去 1 并转换为 int:

a = df['date'].rank(method='dense').sub(1).astype(int)
print (a)
0 1
1 0
2 3
3 4
4 2
Name: date, dtype: int32

Series.rank 中的参数方法 :

method : {'average', 'min', 'max', 'first', 'dense'}

average: average rank of group
min: lowest rank in group
max: highest rank in group
first: ranks assigned in order they appear in the array
dense: like ‘min’, but rank always increases by 1 between groups

关于python - 按原始系列索引的时间顺序返回 pandas 日期时间系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45566406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com