Concatenate DataFrames in Pandas: Stack, Align, and Avoid Duplicate Indexes
pd.concat stacks or aligns DataFrames into a single object, respecting index and column labels. Use axis=0 to stack rows and axis=1 to line columns up side by side. The most common mistake is reusing the old index and ending up with duplicate labels — ignore_index=True fixes that in one line.
What does pd.concat do, and when should you use it instead of merge?
pd.concat is the pandas function for gluing DataFrames on top of each other or side by side. It does not look for a key column: it fits the objects together along an axis, using the index and column labels. merge and join exist for the opposite case, when two tables have to be matched on a shared field such as customer_id or date.
In practice the choice is simple. If both DataFrames have the same columns and hold the same kind of record — January and February sales, for example — use concat. If each table carries different columns that need to be combined through a key, use merge.
- axis=0 (default): stacks rows, one table under the other.
- axis=1: aligns columns, one table next to the other.
- merge and join: match tables by key, not by position.
- concat does not drop duplicates or validate keys; that is merge's job.
How do you stack DataFrames with axis=0 without losing columns?
With axis=0, pandas stacks rows in the order the DataFrames appear in the list. Columns are joined by name: if one DataFrame has a column the other lacks, that column exists in the result and the rows that did not have it receive NaN.
That behavior helps when tables come from sources with slightly different schemas, but it is a trap when the difference is just a typo. revenue and Revenue become two separate columns and the result ends up with half the values in each. Checking df.columns before concatenating saves the cleanup work.
- Check that column names match exactly before stacking.
- Use ignore_index=True to produce a fresh, sequential index.
- Pass a list of DataFrames, not several loose arguments.
- Build the list in a loop and call concat once, at the end.
How do you align tables side by side with axis=1?
With axis=1, pandas does not stack — it aligns. The match is made on index labels, not on row order. If one DataFrame has an index from 0 to 9 and the other from 5 to 14, the result has an index from 0 to 14 and the positions without a partner receive NaN.
That is why axis=1 often breaks after a filter. Filtering rows changes the index, and the alignment then pairs labels that no longer refer to the same rows. reset_index(drop=True) on both sides before concatenating restores alignment by position.
- axis=1 aligns by index label, not by order.
- Filters and sorts shift labels; reset the index first.
- sort=False keeps columns in the order you passed them.
- Check the shape afterwards: extra columns mean labels that did not match.
How do you avoid duplicate indexes after concat?
A duplicate index does not raise an error in concat by default. The result simply repeats labels, and any selection with loc returns more than one row. In larger pipelines that leaks into merge, groupby and reindex.
Three arguments cover most cases: ignore_index=True discards the old index and builds a new RangeIndex; verify_integrity=True raises an error when labels repeat, which works as a test; and keys adds an extra index level that records which DataFrame each row came from.
- ignore_index=True: new index, no repeated labels.
- verify_integrity=True: fail fast if there is a duplicate.
- keys=['jan','feb']: tags the origin of each block of rows.
- reset_index() after concat when you want the old index as a column.
How do you concatenate many files into a single DataFrame?
The most common day-to-day case is joining many files that share the same structure. Instead of reading and concatenating one at a time, build a list of DataFrames and call concat once, at the end.
Concatenating inside the loop works, but every call copies the data already accumulated. With a few files the difference does not show; with many, runtime grows for no reason.
- Read the files in a list comprehension and keep the DataFrames in a list.
- Call pd.concat(frames, ignore_index=True) a single time.
- Add keys=filenames if you need to trace each row back to its file.
- Confirm the row count matches the sum of the parts before moving on.
Where does Pandas fit in a Python for Data Science course?
Pandas is one of the core topics of the Python for Data Science and Analytics course, which runs from zero to advanced. The three main modules — Basic, Intermediate and Advanced — plus bonus modules cover IDE and Jupyter Notebook setup, basic functions, NumPy and Pandas, user-defined functions, loops and conditionals, data visualization, data cleaning and preparation, and outlier detection.
The course closes with a final project: an end-to-end exploratory analysis and machine learning pipeline. It also covers linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection and cross-validation. Lessons are recorded in high quality and watched at your own pace, with guided exercises, real market projects for your portfolio, a certificate of completion, an exclusive community for networking, and unlimited access with no expiry date. You do not need to know how to program before you start. Enrollment goes through the Hotmart checkout, by card or boleto, at R$ 470 or 12 installments of R$ 20,37 on a credit card. Details are on python.paanalytics.net.
- Three main modules plus bonus modules, from zero to advanced.
- Guided exercises and real market projects for your portfolio.
- Certificate of completion and an exclusive community for networking.
- Unlimited access: you keep the course with no expiry date.
| Argument | What it does | When to use it |
|---|---|---|
| axis=0 | Stacks rows from each DataFrame | Same columns, same kind of record |
| axis=1 | Aligns columns by index label | Tables that describe the same rows |
| ignore_index=True | Builds a new sequential RangeIndex | You do not need the original labels |
| verify_integrity=True | Raises an error on repeated labels | You want to catch duplicates early |
| keys=[...] | Adds an index level with the source | You need to trace rows back to a file |
Behavior of the pandas concat arguments as described in the sections above; no product claims.
Learn Pandas from zero to advanced, with a machine learning project
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Does pd.concat modify the original DataFrames?
No. concat returns a new object and leaves the inputs untouched. If you want the result to replace the originals, assign it back to a variable yourself.
What is the difference between ignore_index=True and reset_index()?
ignore_index=True throws the old labels away while the concatenation happens and gives you a clean RangeIndex. reset_index() keeps the old labels as a regular column, which is what you want when the original index carries information such as a date or an ID.
Why did my concatenated DataFrame fill up with NaN?
Two usual causes. With axis=0, a column name that exists in one DataFrame but not the other becomes a new column and the missing rows get NaN. With axis=1, alignment happens by index label, so rows whose labels do not match on both sides also get NaN. Checking df.columns and resetting the index before concatenating removes most of it.
How do I keep track of which file each row came from?
Use the keys argument: pd.concat(frames, keys=filenames) adds an outer index level with the source of each block. You can then select a single file with .loc or turn that level into a column with reset_index().
Do I need to know how to program before starting the course?
No. The course is built from zero to advanced, so it starts with IDE and Jupyter Notebook setup and basic functions before moving into NumPy and Pandas. The Pandas material sits in the main modules, alongside data cleaning, visualization and the machine learning topics that close the course.