Append Two pandas DataFrames with Same Columns in Python (Example Code)
This article illustrates how to append two pandas DataFrames with the same columns in the Python programming language.
Example Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
my_df1 = pd.DataFrame({"A":["yes", "no", "yes", "yes"], # Construct two pandas DataFrames "B":range(0, 4), "C":["hey", "hi", "huhu", "hello"]}) print(my_df1) # A B C # 0 yes 0 hey # 1 no 1 hi # 2 yes 2 huhu # 3 yes 3 hello |
my_df1 = pd.DataFrame({"A":["yes", "no", "yes", "yes"], # Construct two pandas DataFrames "B":range(0, 4), "C":["hey", "hi", "huhu", "hello"]}) print(my_df1) # A B C # 0 yes 0 hey # 1 no 1 hi # 2 yes 2 huhu # 3 yes 3 hello
my_df2 = pd.DataFrame({"A":["foo", "bar", "foo", "foo"], "B":range(11, 15), "C":["a", "b", "a", "d"]}) print(my_df2) # A B C # 0 foo 11 a # 1 bar 12 b # 2 foo 13 a # 3 foo 14 d |
my_df2 = pd.DataFrame({"A":["foo", "bar", "foo", "foo"], "B":range(11, 15), "C":["a", "b", "a", "d"]}) print(my_df2) # A B C # 0 foo 11 a # 1 bar 12 b # 2 foo 13 a # 3 foo 14 d
Example: Appending Two pandas DataFrames with Same Variables
my_df_combined = pd.concat([my_df1, my_df2]) # Combine two DataFrames print(my_df_combined) # A B C # 0 yes 0 hey # 1 no 1 hi # 2 yes 2 huhu # 3 yes 3 hello # 0 foo 11 a # 1 bar 12 b # 2 foo 13 a # 3 foo 14 d |
my_df_combined = pd.concat([my_df1, my_df2]) # Combine two DataFrames print(my_df_combined) # A B C # 0 yes 0 hey # 1 no 1 hi # 2 yes 2 huhu # 3 yes 3 hello # 0 foo 11 a # 1 bar 12 b # 2 foo 13 a # 3 foo 14 d
Further Resources & Related Articles
In addition, you could have a look at the related tutorials on this homepage. I have released numerous articles already.