I have a dataframe like this :
Date Price 0 2021-02-12 00:00:00 50 1 2021-02-11 00:00:00 2 2 2021-02-10 00:00:00 40.4 3 2021-02-09 00:00:00 775.6 4 2021-02-08 00:00:00 1000.2 5 2021-02-07 00:00:00 500
Columns’ types with print(df.dtypes) :
Date datetime64[ns] Price float64
Expected Output :
Date Price 0 2021-02-07 00:00:00 500 1 2021-02-08 00:00:00 1000.2 2 2021-02-09 00:00:00 775.6 3 2021-02-10 00:00:00 40.4 4 2021-02-11 00:00:00 2 5 2021-02-12 00:00:00 50
I have a dataframe like df. When I do :
df = df.sort_values(by='Date')
But nothing happen even by adding ascending = True or False.
Could you give the way pls to order this dataframe as above ?
If possible can you give the 2 possibilites like ordering by index and date but I’m looking to order by ascending date directly without touching to the index.
EDIT for more clarity :
# Converted list of dictionaries to a Dataframe extracted_data_List_DataFrames = [pd.DataFrame(x) for x in extracted_data_List] # Convert string to their respectiv types for dfs in extracted_data_List_DataFrames: dfs['Date'] = pd.to_datetime(dfs['Date']) dfs['Price'] = dfs['Price'].astype('float64') # Sort dataframes by 'Date' dfs = dfs.sort_values(['Date'], ascending=False) print(extracted_data_List_DataFrames)
You have my code above. I’m not able to make the sort method to work correctly.
Advertisement
Answer
Problem is if modify values in loop there is no change if original list, you can assign ouput to original list of DataFrames like:
for i, dfs in enumerate(extracted_data_List_DataFrames): dfs['Date'] = pd.to_datetime(dfs['Date']) dfs['Price'] = dfs['Price'].astype('float64') # Sort dataframes by 'Date' dfs = dfs.sort_values(['Date'], ascending=False) extracted_data_List_DataFrames[i] = dfs
Another idea is use inplace=True
:
for dfs in extracted_data_List_DataFrames: dfs['Date'] = pd.to_datetime(dfs['Date']) dfs['Price'] = dfs['Price'].astype('float64') # Sort dataframes by 'Date' dfs.sort_values(['Date'], ascending=False, inplace=True)