The below two dataframes df1 and df2 have been manually entered into Python. Then the dataframes were merged into df3. How can I make sure that the final merged dataframe df3 is using the same descending (chronological) order (as for the initial dataframes df1 and df2)(as it is not a case by default)? Thanks in advance
import pandas as pd
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-4-7', '2021-4-18', '2021-5-12'],
"x": [3, 3, 3, 0 ]})
df1['date'] = pd.to_datetime(df1['date'])
df1.set_index('date', inplace=True)
df1
x
date
2021-03-22 3
2021-04-07 3
2021-04-18 3
2021-05-12 0
df2 = pd.DataFrame({"date": ['2021-3-22', '2021-4-8', '2021-4-18', '2021-5-12'],
"y": [3, 3, 3, 0 ]})
df2['date'] = pd.to_datetime(df2['date'])
df2.set_index('date', inplace=True)
df2
y
date
2021-03-22 3
2021-04-08 3
2021-04-18 3
2021-05-12 0
df3 = df1.merge(df2, on='date', how='outer')
df3
x y
date
2021-03-22 3.0 3.0
2021-04-07 3.0 NaN
2021-04-18 3.0 3.0
2021-05-12 0.0 0.0
2021-04-08 NaN 3.0
PS this question is a followup question to: how to enter manually a Python dataframe with daily dates in a correct format
CodePudding user response:
To arrange the merged dataframe in descending order, you can update the merge line with this
df3 = df1.merge(df2, on='date', how='outer').sort_values(by='date', ascending=False)
This will sort df3 in descending chronological order.