Right way to reverse pandas.DataFrame?

后端 未结 6 1019
旧巷少年郎
旧巷少年郎 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: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 )

提交回复
热议问题