为了账号安全,请及时绑定邮箱和手机立即绑定

将多索引转换为单个日期

将多索引转换为单个日期

LEATH 2023-07-11 13:53:45
我有一个数据框,其中索引是多重索引,如下所示;     1     2     3     4     52020 6     7     8     9     10     11     12由于我需要每日值,我希望将其转换为如下列;Date2020/01/012020/02/012020/03/012020/04/012020/05/01etc 这样我就可以使用;df.set_index('Date').resample('D').ffill()非常感谢任何帮助!
查看完整描述

1 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

如果索引中只有year并且month级别使用列表理解并更改连接字符串的格式:


#python 3

df.index = pd.to_datetime([f'{a}-{b}-01' for a, b in df.index])


#python 2

df.index = pd.to_datetime(['{}-{}-01'.format(a, b) for a, b in df.index])

如果还有天:


#python 3

df.index = pd.to_datetime([f'{a}-{b}-{c}' for a, b, c in df.index])


#python 2

df.index = pd.to_datetime(['{}-{}-{}'.format(a, b, c) for a, b, c in df.index])

进而:


df1 = df.resample('D').ffill()


查看完整回答
反对 回复 2023-07-11
  • 1 回答
  • 0 关注
  • 60 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信