Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concating pandas dataframe

Tags:

python

pandas

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
like image 734
Zanam Avatar asked Apr 19 '17 19:04

Zanam


People also ask

How do I concatenate pandas DataFrame?

Use DataFrame.append() method to concatenate DataFrames on rows. For E.x, df. append(df1) appends df1 to the df DataFrame.

How do I concatenate a different DataFrame in Python?

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.

What is difference between pandas concat and merge?

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.

How concatenate two columns of different DataFrames in pandas?

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.


1 Answers

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
like image 157
SillyPerson Avatar answered Nov 14 '22 23:11

SillyPerson