How can I sort DataFrame by date in Python?

前端 未结 3 622
难免孤独
难免孤独 2021-01-19 22:16

I try to sort dataframe shown below by date using df.sort_values(by=\'date\') however it doesn\'t work. Any ideas how can I do this to be sure that it is sorted

相关标签:
3条回答
  • 2021-01-19 22:19

    If you have a dataframe like this below:

    df = pd.DataFrame({'col1' : ['A', 'A', 'B', np.nan, 'D', 'C'],
    'col2' : [2, 1, 9, 8, 7, 4],
    'col3': [0, 1, 9, 4, 2, 3], })
    

    This is how you sort it:

    df = df.sort_values(by=['col1'])
    

    Similar problem with solution on stackoverflow: how to sort pandas dataframe from one column Panda reference : http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.sort.html

    0 讨论(0)
  • 2021-01-19 22:25

    df.sort_values() returns sorted DF, but it doesn't sort in place.

    So either use:

    df = df.sort_values(by='date') 
    

    or

    df.sort_values(by='date', inplace=True)
    
    0 讨论(0)
  • 2021-01-19 22:34

    Try

    df['Date']=pd.to_datetime(df.Date)
    df.sort_values(['Date'])
    
    0 讨论(0)
提交回复
热议问题