Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack two pandas data frames

Tags:

python

pandas

How do I stack the following 2 dataframes:

df1     hzdept_r    hzdepb_r    sandtotal_r 0   0           114         0 1   114         152         92.1  df2     hzdept_r    hzdepb_r    sandtotal_r 0   0           23          83.5 1   23          152         45 

to give the following result:

    hzdept_r    hzdepb_r    sandtotal_r 0   0           114         0 1   114         152         92.1 2   0           23          83.5 3   23          152         45 

Using the pandas merge operations does not work since it just lines the dataframes horizontally (and not vertically, which is what I want)

like image 595
user308827 Avatar asked Mar 30 '15 16:03

user308827


People also ask

How do you stack data frames in Python?

DataFrame - stack() function The stack() function is used to stack the prescribed level(s) from columns to index. Return a reshaped DataFrame or Series having a multi-level index with one or more new inner-most levels compared to the current DataFrame.

Can we add 2 DataFrames in Python?

To append the rows of one dataframe with the rows of another, we can use the Pandas append() function. With the help of append(), we can append columns too. Let's take an example and see how to use this method.

How do you add two DataFrames on top of each other?

Merge. Another widely used function to combine DataFrames is merge(). Concat() function simply adds DataFrames on top of each other or adds them side-by-side.

Can we append multiple DataFrames in pandas?

pandas. DataFrame. append() method is used to append one DataFrame row(s) and column(s) with another, it can also be used to append multiple (three or more) DataFrames.


1 Answers

In [5]: a = pd.DataFrame(data=np.random.randint(0,100,(2,5)),columns=list('ABCDE'))  In [6]: b = pd.DataFrame(data=np.random.randint(0,100,(2,5)),columns=list('ABCDE'))  In [7]: c = pd.concat([a,b],ignore_index=True)  In [8]: c Out[8]:      A   B   C   D   E 0  12  56  62  35  20 1  10  71  63   0  70 2  61  72  29  10  71 3  88  82  39  73  94 
like image 102
tnknepp Avatar answered Sep 27 '22 02:09

tnknepp