append()
adds rows of other to the end of caller, returning a new object. The following is the basic syntax of append(), in which df_1 is the main one, and df_2 will be appended into df_1.
df_1.append(df_2)
The following is the dataframes that will be used later in the examples.
import pandas as pd
# create a dataframe called df_1
df_1 = pd.DataFrame({'Brand': ['Tesla', 'Toyota','Tesla','Ford'],
'Location': ['CA', 'CA','NY','MA']},index=list('abcd'))
print("df_1: \n",df_1 )
# create a dataframe called df_2
df_2 = pd.DataFrame({'Brand': ['Honda', 'Toyota'],
'Location': ['CA', 'WA']},index=list('tj'))
print("df_2: \n",df_2)
# create a dataframe called df_3
df_3 = pd.DataFrame({
'Name': ['Jake', 'Jacob','John','Jess','James']},index=list('abdek'))
print("df_3: \n",df_3)
df_1: Brand Location a Tesla CA b Toyota CA c Tesla NY d Ford MA df_2: Brand Location t Honda CA j Toyota WA df_3: Name a Jake b Jacob d John e Jess k James
Example 1: append df_2 to df_1
# appending df_2 into df_1
appended_df=df_1.append(df_2)
print(appended_df)
Brand Location a Tesla CA b Toyota CA c Tesla NY d Ford MA t Honda CA j Toyota WA
Example 2: append df_2 into df_1
# appending df_2 into df_1
appended_df=df_1.append(df_3)
print(appended_df)
Brand Location Name a Tesla CA NaN b Toyota CA NaN c Tesla NY NaN d Ford MA NaN a NaN NaN Jake b NaN NaN Jacob d NaN NaN John e NaN NaN Jess k NaN NaN James
Note that, this is very different from merge().
# using merge()
merged_df=df_1.merge(df_3, how='outer',left_index=True,right_index=True)
print(merged_df)
Brand Location Name a Tesla CA Jake b Toyota CA Jacob c Tesla NY NaN d Ford MA John e NaN NaN Jess k NaN NaN James