Join two columns with different dates

Asked

Viewed 37 times

1

I have two dfs:

1 - Quotation of a share of the month of January-2020 (23 lines)

2 - Quotation of a share of the month of January-2021 (23 lines)

I need to put all this together in a single date table, that is, the date of 2020 can be 2021 or vice versa, as long as they stay on the same line as if they were on the same date. When I merge or reindex, because they are different dates it returns null values for one of the columns.

df_sp1 = DataReader('^GSPC', data_source='yahoo', start='2020-1-1', end="2020-02-04")
df_sp2 = DataReader('^GSPC', data_source='yahoo', start='2021-1-1')

df_sp2["2020"] = df_sp1["Adj Close"]
df_sp2

Thank you.

  • Welcome to the stackoverflow community. Could post the code?

  • I edited the code. This was one of several attempts, the added column gets null values, because the dates (index) are different.

  • Jesse, please state which exit df_sp2 and what the output would you like to see

1 answer

0


...

df_sp1 = DataReader('^GSPC', data_source='yahoo', start='2020-1-1', end="2020-02-04")
df_sp2 = DataReader('^GSPC', data_source='yahoo', start='2021-1-1')

You can use the Concat

novo_df = pd.concat([df_sp2.reset_index(), df_sp1['Adj Close'].reset_index(drop = True).rename('2020')], axis = 1).set_index('Date')

Exit

                   High         Low        Open       Close     Volume    Adj Close  2020
Date                            
2021-01-04  3769.989990 3662.709961 3764.610107 3700.649902 5006680000  3700.649902 3257.850098
2021-01-05  3737.830078 3695.070068 3698.020020 3726.860107 4582620000  3726.860107 3234.850098
2021-01-06  3783.040039 3705.340088 3712.199951 3748.139893 6049970000  3748.139893 3246.280029

...

  • 1

    Thank you very much. That was it!

  • @Jesséfelício, good morning! For nothing! Big hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.