Join 2 datasets that have different levels

Viewed 26

I want to join two dataframes, but one of them is multi-indexed like so:

Multi-level dataframe

The other dataframe is much simpler:

Basic dataframe

How can I join these two dataframes while still preserving the multi-level structure of the first dataframe?

This is what I'm getting at the moment:

Only one level for the merged dataframe

1 Answers

There is several solution to your problem. I think you can use concat or merge from panda library. I hope it will help you:

import panda as pd

dataframe1 = (pd.read_csv('test1.csv', sep=';', header=0, index_col=0, parse_dates=True, squeeze=True))
dataframe2 = (pd.read_csv('test2.csv', sep=';', header=0, index_col=0, parse_dates=True, squeeze=True))

dataframe3 = pd.concat([dataframe1, dataframe2], axis=1, join='inner') # using concat
dataframe4 = pd.merge(dataframe1, dataframe2, left_index=True, right_index=True) # using merge

#export to csv
dataframe3.to_csv('test3.csv', sep=';', header=True, index=True)
dataframe4.to_csv('test4.csv', sep=';', header=True, index=True)

What do you think about this ?

Related