I have following dataframe:
df1 = pd.DataFrame.from_dict({'A':[3,5,1,7], 'DateTime' : pd.date_range("11:00", "14:00", freq="60min")}).set_index('DateTime')
df2 = pd.DataFrame.from_dict({'B':[13,15,1,17], 'DateTime' : pd.date_range("12:00", "15:00", freq="60min")}).set_index('DateTime')
I am trying the following:
pd.concat([df1, df2], join='outer')
A B
DateTime
2017-04-19 11:00:00 3.0 NaN
2017-04-19 12:00:00 5.0 NaN
2017-04-19 13:00:00 1.0 NaN
2017-04-19 14:00:00 7.0 NaN
2017-04-19 12:00:00 NaN 13.0
2017-04-19 13:00:00 NaN 15.0
2017-04-19 14:00:00 NaN 1.0
2017-04-19 15:00:00 NaN 17.0
How do I get the following instead:
A B
DateTime
2017-04-19 11:00:00 3.0 NaN
2017-04-19 12:00:00 5.0 13.0
2017-04-19 13:00:00 1.0 15.0
2017-04-19 14:00:00 7.0 1.0
2017-04-19 15:00:00 NaN 17.0
Use DataFrame.append() method to concatenate DataFrames on rows. For E.x, df. append(df1) appends df1 to the df DataFrame.
We'll pass two dataframes to pd. contact() method in the form of a list and mention in which axis you want to concat, i.e. axis=0 to concat along rows, axis=1 to concat along columns.
merge() for combining data on common columns or indices. . join() for combining data on a key column or an index. concat() for combining DataFrames across rows or columns.
It is possible to join the different columns is using concat() method. DataFrame: It is dataframe name. axis: 0 refers to the row axis and1 refers the column axis. join: Type of join.
You need to set the axis to 1.
pd.concat([df1, df2], join='outer', axis=1)
A B
DateTime
2017-04-19 11:00:00 3.0 NaN
2017-04-19 12:00:00 5.0 13.0
2017-04-19 13:00:00 1.0 15.0
2017-04-19 14:00:00 7.0 1.0
2017-04-19 15:00:00 NaN 17.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With