Daniel
Daniel

Reputation: 165

Python Pandas process and merge non-matching time series as a dataframe

I have the following two csv files:

enter image description here

enter image description here

and I want to load them in python and merge them into a single dataframe which looks like this:

enter image description here

Any help is appreciated

Upvotes: 0

Views: 481

Answers (2)

You don not really explain what your issue is with what you are trying to do but I suspect that you encounter problems joining on dates. Here is a solution:

import pandas as pd
import numpy as np



Stock1 = [11.2,22.2,33.2,442,55.2,66,77,38.4]
Stock2 = [33.2,442,55.2,66,77,38.4]
begin_date1 = '2019-10-16'
begin_date2 = '2019-10-18'

df = pd.DataFrame({'dates':pd.date_range(begin_date1, periods=len(Stock1)),
                   'Stock1':Stock1 })
df2 = pd.DataFrame({'dates':pd.date_range(begin_date2, periods=len(Stock2)),
                   'Stock2':Stock2 })

DF=pd.merge(df,df2, how='outer', left_index=True, right_index=True)

enter image description here

I have created my own dataframes but it works just as well with yours.

Upvotes: 1

Sander van den Oord
Sander van den Oord

Reputation: 12808

Using pd.merge() should work:

df1 = pd.read_csv('file1.csv', header=0)
df2 = pd.read_csv('file2.csv', header=0)

result = pd.merge(df1, df2, on='Date', how='outer')

Please check out this interesting post on how merging works:
Pandas Merging 101

Pandas docs on merging:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

Upvotes: 1

Related Questions