【问题标题】:How to index a date column in python如何在python中索引日期列
【发布时间】:2017-09-17 04:03:31
【问题描述】:

我在 python 数据框中有一个日期列。我想通过订购日期来索引这些。这在python中有可能吗?

date     indexed
2007-02-21  3
2007-02-18  1
2007-02-24  5
2007-02-18  1
2007-02-23  4
2007-02-20  2
2007-02-23  4

我正在寻找索引,但我想我使用了错误的术语来检查。请指导。

编辑

实际上我想用等效的索引号替换日期。

【问题讨论】:

标签: python pandas


【解决方案1】:

IIUC你想用pd.factorize()方法:

In [190]: df['new'] = pd.factorize(df['date'], sort=True)[0] + 1

In [191]: df
Out[191]:
        date  indexed  new
0 2007-02-21        3    3
1 2007-02-18        1    1
2 2007-02-24        5    5
3 2007-02-18        1    1
4 2007-02-23        4    4
5 2007-02-20        2    2
6 2007-02-23        4    4

PS pd.factorize()0 开始计数,所以我添加了1 以满足您想要的结果

【讨论】:

  • 非常感谢。为什么我们在这里加 1?请澄清
  • @DoubtDhanabalu, pd.factorize()0 开始。所以我添加了1 以满足您想要的结果
  • 好的,我知道了,非常感谢。我接受这个答案。再次感谢。
【解决方案2】:

您要查找的是按日期排序的值

df = pd.DataFrame(["2007-02-21","2007-02-18","2007-02-24","2007-02-18","2007-02-23","2007-02-20","2007-02-23"],columns=["date"])

df.sort_values("date", axis=0)

【讨论】:

    【解决方案3】:

    使用pandas.DataFrame.sort_index

    import pandas as pd
    
    df = pd.DataFrame(['2007-02-21','2007-02-18','2007-02-24','2007-02-18','2007-
    02-23', '2007-02-20' , '2007-02-23'], index=[3, 1, 5, 1, 4,2,4], columns=
    ['Date'])
    
    print df
             Date
    3  2007-02-21
    1  2007-02-18
    5  2007-02-24
    1  2007-02-18
    4  2007-02-23
    2  2007-02-20
    4  2007-02-23
    
    
    df2 = df.sort_index(axis=0)
    print(df2)
    
             Date
    1  2007-02-18
    1  2007-02-18
    2  2007-02-20
    3  2007-02-21
    4  2007-02-23
    4  2007-02-23
    5  2007-02-24
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-31
      • 2019-03-12
      • 2016-10-03
      • 2022-01-10
      • 2012-02-26
      • 2020-01-02
      • 2020-11-21
      • 1970-01-01
      相关资源
      最近更新 更多