Right way to reverse pandas.DataFrame?

后端 未结 6 973
旧巷少年郎
旧巷少年郎 2020-11-27 11:24

Here is my code:

import pandas as pd

data = pd.DataFrame({\'Odd\':[1,3,5,6,7,9], \'Even\':[0,2,4,6,8,10]})

for i in reversed(data):
    print(data[\'Odd\']         


        
相关标签:
6条回答
  • 2020-11-27 11:44

    This works:

        for i,r in data[::-1].iterrows():
            print(r['Odd'], r['Even'])
    
    0 讨论(0)
  • 2020-11-27 11:47

    You can reverse the rows in an even simpler way:

    df[::-1]
    
    0 讨论(0)
  • 2020-11-27 11:52
    data.reindex(index=data.index[::-1])
    

    or simply:

    data.iloc[::-1]
    

    will reverse your data frame, if you want to have a for loop which goes from down to up you may do:

    for idx in reversed(data.index):
        print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])
    

    or

    for idx in reversed(data.index):
        print(idx, data.Even[idx], data.Odd[idx])
    

    You are getting an error because reversed first calls data.__len__() which returns 6. Then it tries to call data[j - 1] for j in range(6, 0, -1), and the first call would be data[5]; but in pandas dataframe data[5] means column 5, and there is no column 5 so it will throw an exception. ( see docs )

    0 讨论(0)
  • 2020-11-27 11:55

    The right way to do this is:

    data = data.sort_index(ascending=False)
    

    This approach has the benefits of (1) being a single line, (2) not requiring a utility function, and most importantly (3) not actually changing any of the data in the dataframe.

    0 讨论(0)
  • 2020-11-27 12:02

    None of the existing answers resets the index after reversing the dataframe.

    For this, do the following:

     data[::-1].reset_index()
    

    Here's a utility function that also removes the old index column, as per @Tim's comment:

    def reset_my_index(df):
      res = df[::-1].reset_index(drop=True)
      return(res)
    

    Simply pass your dataframe into the function

    0 讨论(0)
  • 2020-11-27 12:06

    The simplest solution might be

    data = data[::-1]
    
    0 讨论(0)
提交回复
热议问题