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
JavaScript
x
40
40
1
import pandas as pd
2
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-4-7', '2021-4-18', '2021-5-12'],
3
"x": [3, 3, 3, 0 ]})
4
df1['date'] = pd.to_datetime(df1['date'])
5
df1.set_index('date', inplace=True)
6
df1
7
8
x
9
date
10
2021-03-22 3
11
2021-04-07 3
12
2021-04-18 3
13
2021-05-12 0
14
15
df2 = pd.DataFrame({"date": ['2021-3-22', '2021-4-8', '2021-4-18', '2021-5-12'],
16
"y": [3, 3, 3, 0 ]})
17
df2['date'] = pd.to_datetime(df2['date'])
18
df2.set_index('date', inplace=True)
19
df2
20
21
y
22
date
23
2021-03-22 3
24
2021-04-08 3
25
2021-04-18 3
26
2021-05-12 0
27
28
df3 = df1.merge(df2, on='date', how='outer')
29
df3
30
31
32
x y
33
date
34
2021-03-22 3.0 3.0
35
2021-04-07 3.0 NaN
36
2021-04-18 3.0 3.0
37
2021-05-12 0.0 0.0
38
2021-04-08 NaN 3.0
39
40
PS this question is a followup question to: how to enter manually a Python dataframe with daily dates in a correct format
Advertisement
Answer
To arrange the merged dataframe in descending order, you can update the merge line with this
JavaScript
1
2
1
df3 = df1.merge(df2, on='date', how='outer').sort_values(by='date', ascending=False)
2
This will sort df3 in descending chronological order.