How to append two DataFrames in Pandas?

PythonServer Side ProgrammingProgramming

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.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df1.
  • Print the input DataFrame, df1.
  • Create another DataFrame, df2, with the same column names and print it.
  • Use the append method, df1.append(df2, ignore_index=True), to append the rows of df2 with df2.
  • Print the resultatnt DataFrame.

Example

import pandas as pd

df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"x": [1, 3], "y": [1, 9], "z": [29, 30]})

print "Input DataFrame 1 is:\n", df1
print "Input DataFrame 2 is:\n", df2

df3 = df1.append(df2, ignore_index=True)

print "After appending, DataFrame is: \n", df3

Output

Input DataFrame 1 is:
  x y z
0 5 4 9
1 2 7 3

Input DataFrame 2 is:
  x y  z
0 1 1 29
1 3 9 30

After appending, DataFrame is:
  x y z
0 5 4 9
1 2 7 3
2 1 1 29
3 3 9 30

Now, let's use different column names for the dataframes and use the append() function without ignore_index parameter. The default value of ignore_index is False.

import pandas as pd

df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"a": [1, 3], "b": [1, 9], "c": [29, 30]})


print "Input DataFrame 1 is:\n", df1 
print "Input DataFrame 2 is:\n", df2 


df3 = df1.append(df2)


print "After appending, DataFrame is: \n", df3 

Now, it will produce the following output

Input DataFrame 1 is:
  x y z
0 5 4 9
1 2 7 3

Input DataFrame 2 is:
  a b  c
0 1 1 29
1 3 9 30

After appending, DataFrame is:
  x     y    z    a    b    c
0 5.0  4.0  9.0  NaN  NaN  NaN
1 2.0  7.0  3.0  NaN  NaN  NaN
0 NaN  NaN  NaN  1.0  1.0  29.0
1 NaN  NaN  NaN  3.0  9.0  30.0
raja
Published on 15-Sep-2021 07:05:04
Advertisements