【问题标题】:date index from from multiindex for pandas dataframe来自 pandas 数据框的 multiindex 的日期索引
【发布时间】:2020-04-20 19:40:21
【问题描述】:

我有一个带有多索引的数据框,我想将其转换为date() 索引。

这是我拥有的数据帧类型的示例模拟:

i = pd.date_range('01-01-2016', '01-01-2020')
x = pd.DataFrame(index = i, data=np.random.randint(0, 10, len(i)))
x = x.groupby(by = [x.index.year, x.index.month]).sum()
print(x)

我尝试通过以下方式将其转换为日期索引:

def to_date(ind):
    return pd.to_datetime(str(ind[0]) + '/' + str(ind[1]), format="%Y/%m").date()

# flattening the multiindex to tuples to later reset the index
x.set_axis(x.index.to_flat_index(), axis=0, inplace = True)    

x = x.rename(index = to_date)

x.set_axis(pd.DatetimeIndex(x.index), axis=0, inplace=True)

但是速度很慢。我认为问题出在pd.to_datetime(str(ind[0]) + '/' + str(ind[1]), format="%Y/%m").date() 行。非常感谢任何让这更快的想法。

【问题讨论】:

    标签: python python-3.x pandas datetime multi-index


    【解决方案1】:

    你可以使用:

    x.index=pd.to_datetime([f"{a}-{b}" for a,b in x.index],format='%Y-%m')
    print(x)
    

                0
    2016-01-01  162
    2016-02-01  119
    2016-03-01  148
    2016-04-01  125
    2016-05-01  132
    2016-06-01  144
    2016-07-01  157
    2016-08-01  141
    2016-09-01  138
    2016-10-01  168
    2016-11-01  140
    2016-12-01  137
    2017-01-01  113
    2017-02-01  113
    2017-03-01  155
    ..........
    ..........
    ......
    

    【讨论】:

    • 你是对的,它快了 10 倍。但为什么?代码中的想法几乎是一样的。
    • @guyguyguy12345 是的,但是那里的操作太多了,还有一些功能,例如:set_index 对数据帧进行操作,而不是仅对索引进行操作。但是这个方法只是使用索引列表来操作。
    猜你喜欢
    • 2015-09-05
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2014-01-30
    • 2021-08-14
    • 2012-08-24
    相关资源
    最近更新 更多