Does concatenating dataframes preserve row order?

Question

In the context of this exercise, does concatenating dataframes preserve row order?

Answer

Yes, by default, concatenating dataframes will preserve their row order. The order of the dataframes to concatenate will be the order of the result dataframe.

One way to think of the concat method is that it just stacks a dataframe on top of another dataframe.

For example,
pd.concat([df1, df2, df3])
will result in a dataframe with the rows of df1 stacked on top of the rows of df2, which will be stacked on top of the rows in df3, preserving their initial row order.

In addition, by default, duplicate rows will be included when concatenating dataframes. So,
pd.concat([df1, df1])
will result in having the dataframe df1 on top of itself with all rows duplicated.

5 Likes

Wanna share a piece of info:
Even if the columns of two dataframes are not the same, upon concatenating, the resulting dataframe apply the order of columns same as the 1st one.

say in this exercise, I changed order of ice_cream, such that the order is price → item
When concatenating bakery and inverted ice_cream, the resulting dataframe should the order: item -→ price.

5 Likes