简体   繁体   中英

Pandas sort_values method not sorting Pandas DataFrame

I am trying to sort a dataframe, but the sort_values method seems not to be working. I have checked other stackoverflow posts on the same issue, but they do not seem to help me.

Code.py

    var_df = pd.DataFrame(columns=['Variable','Remaining values','Degrees'])
    var_df.loc[0] = ['V1', 1, 2]
    var_df.loc[1] = ['V2', 2, 3]
    var_df.loc[2] = ['V3', 2, 1]
    var_df.loc[3] = ['V4', 4, 5]
    var_df.loc[4] = ['V5', 5, 4]
    var_df.loc[5] = ['V6', 5, 7]
    var_df.loc[6] = ['V7', 6, 1]
    
    print(var_df)
    print('\n------------\n')
    
    new_var_df = var_df.sort_values(by=['Remaining values', 'Degrees'], inplace=True, ascending=[True, False])
    new_var_df = var_df.reset_index(drop=True)
    print(new_var_df)

When I print out var_df , and new_var_df , they have the same output:

   Variable Remaining values Degrees
0       V1                1       2
1       V2                2       3
2       V3                2       1
3       V4                4       5
4       V6                5       7
5       V5                5       4
6       V7                6       1

This is the output I am expecting after sorting

排序后的预期输出

分配那么你不需要inplace

new_var_df = var_df.sort_values(by=['Remaining values', 'Degrees'], ascending=[True, False])

Thanks @Yashar.

The problem was caused by a typo on my end. I was resetting the index of the wrong DataFrame( var_df ), instead of new_var_df .

I solved it by changing this new_var_df = var_df.reset_index(drop=True) to

new_var_df = new_var_df.reset_index(drop=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM