python - 如何在Python中为日期列建立索引

标签 python pandas

我在 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

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

编辑

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

最佳答案

您想使用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以满足您想要的结果

关于python - 如何在Python中为日期列建立索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257573/

相关文章:

python - 缺少可选依赖项 'tables' 。在 Pandas to_hdf

python - Pandas 时间序列,在一列上分箱并累积在分箱中花费的时间

python - 如何安排实验在 Azure ML SDK 中每天运行

python - PyOpenCL vs Clyther vs 纯 OpenCL 和 C99 : what's the best for novice?

Python 帮助,打印列表中的值

python - 表征股票市场神经网络的 Keras 损失和准确性

python - 收到错误并没有返回 HttpResponse 对象。到底是怎么回事?

python - 在Python中管道合并多个pandas数据帧

python - 使用 pandas 使用时间作为自变量滚动 OLS

Python从特定日期中提取周数