Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › Concatenate DataFrames in Pandas: Stack, Align, and Avoid Du

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.

Topics: pandas, concat, dataframes

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.

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.

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.

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.

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.

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.

ArgumentWhat it doesWhen to use it
axis=0Stacks rows from each DataFrameSame columns, same kind of record
axis=1Aligns columns by index labelTables that describe the same rows
ignore_index=TrueBuilds a new sequential RangeIndexYou do not need the original labels
verify_integrity=TrueRaises an error on repeated labelsYou want to catch duplicates early
keys=[...]Adds an index level with the sourceYou 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 site

Frequently 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.

Ler em português →