pandas crashes on repeated DataFrame.reset_index()

前端 未结 1 793
故里飘歌
故里飘歌 2021-02-05 00:38

Very weird bug here: I\'m using pandas to merge several dataframes. As part of the merge, I have to call reset_index several times. But when I do, it crashes unexpectedly on t

相关标签:
1条回答
  • 2021-02-05 01:16

    Inspecting frame.py, it looks like pandas tries to insert a column 'index' or 'level_0'. If either/both(??) of them are already taken, then it throws the error.

    Fortunately, there's a "drop" option. AFAICT, this drops an existing index with the same name and replaces it with the new, reset index. This might get you in trouble if you have a column named "index," but I think otherwise you're okay.

    "Fixed" code:

    import pandas
    A = pandas.DataFrame({
        'val' :  ['aaaaa', 'acaca', 'ffffffffd', 'zzzzz'],
        'extra' : range(10,14),
    })
    A = A.reset_index(drop=True)
    A = A.reset_index(drop=True)
    A = A.reset_index(drop=True)
    
    0 讨论(0)
提交回复
热议问题