Search code examples
pythonpandasreverseassignreindex

Python DataFrame not getting saved. How to permanently assign it?


I assigned the dataframe to itself by reversing its index. But when I call it again, it's showing the old dataframe without reversing it.

apple = apple.reindex(index = apple.index[::-1])
apple.head()

Any help would be appreciated. Thanks in advance :)


Solution

  • For me it works nice.

    np.random.seed(45)
    apple = pd.DataFrame(np.random.randint(10, size=(3,4)), 
                         columns=list('abcd'), 
                         index=list('ABC'))
    
    print (apple)
       a  b  c  d
    A  3  0  5  3
    B  4  9  8  1
    C  5  9  6  8
    
    apple = apple.reindex(index = apple.index[::-1])
    print (apple)
       a  b  c  d
    C  5  9  6  8
    B  4  9  8  1
    A  3  0  5  3
    

    Another solution with DataFrame.iloc:

    apple = apple.iloc[::-1]
    print (apple)
       a  b  c  d
    C  5  9  6  8
    B  4  9  8  1
    A  3  0  5  3