
Sponsored
Sponsored
The most straightforward way to concatenate two DataFrames vertically in Python is by using the pandas.concat function. This function allows you to combine multiple DataFrames along either the rows or columns, specified by the axis parameter. Setting axis=0 will stack the DataFrames on top of each other.
Time Complexity: O(n + m), where n and m are the number of rows in df1 and df2, respectively.
Space Complexity: O(n + m) for storing the new concatenated DataFrame.
1import pandas as pd
2
3def concatenate_dataframes(df1, df2This Python solution uses the pandas library to concatenate df1 and df2. The pd.concat function combines the two DataFrames by stacking them on top of each other, specified by axis=0. Setting ignore_index=True reassigns an automatic sequential index to the concatenated DataFrame.
This approach involves manually appending rows from the second DataFrame to the first. This could be slower compared to built-in function calls but provides a clear understanding of what's happening under-the-hood when DataFrames are concatenated.
Time Complexity: O(n + m), similar to the concatenation function, but with additional overhead due to manual row iteration.
Space Complexity: O(n + m) for storing the combined rows in a new DataFrame.
1import pandas as pd
2
3 def concatenate_dataframes_manually(df1, df2):
4 df1_rows = [row for _, row in df1.iterrows()]
5 df2_rows = [row for _, row in df2.iterrows()]
6 all_rows = df1_rows + df2_rows
7 combined_df = pd.DataFrame(all_rows, columns=df1.columns)
8 return combined_dfThis Python solution manually creates a list of rows from both df1 and df2 using the iterrows() function. It concatenates these lists to form a complete list of rows and constructs a new DataFrame from it.