You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为DataFrame中相同日期的行设置相同索引?

为相同日期的行设置相同索引

原始DataFrame

Date            Tic      CLose
0   01/03/2022      AAPL     34.08
1   01/03/2022      HD       22.05
2   02/03/2022      AAPL     39.43
3   02/03/2022      HD       55.45

期望输出

Date            Tic      CLose
0   01/03/2022      AAPL     34.08
0   01/03/2022      HD       22.05
1   02/03/2022      AAPL     39.43
1   02/03/2022      HD       55.45

解决方案

有两种简洁的方法可以实现需求:

方法1:使用pandas.factorize()

该方法会将日期列转换为连续的整数标签,相同日期对应相同标签,直接赋值给索引即可:

import pandas as pd

# 假设你的DataFrame名为df
df.index = pd.factorize(df['Date'])[0]

方法2:使用groupby+ngroup()

通过按日期分组,再给每组分配连续的组编号,作为新索引:

df.index = df.groupby('Date').ngroup()

两种方法都能快速实现将相同日期的行设置为相同连续整数索引的效果。

内容的提问来源于stack exchange,提问作者Abo_nosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:10:34