Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende concat() | s1
Track DA with Py - Data Manipulation with pandas

bookconcat()

Desliza para mostrar el menú

When you need to combine multiple DataFrames in pandas, the concat() function provides a flexible way to stack them either vertically or horizontally. The primary use cases for concat() are to join DataFrames along a particular axis—either stacking rows on top of each other (vertical concatenation) or joining columns side by side (horizontal concatenation). This is especially useful when you have separate datasets with the same structure that you want to combine into a single DataFrame, or when you want to align different datasets with possibly different columns. The concat() function can also handle more complex scenarios, such as combining DataFrames with different columns or adding hierarchical keys to the result for better organization.

12345678910111213141516
import pandas as pd # Create two DataFrames with matching columns df1 = pd.DataFrame({ "Name": ["Alice", "Bob"], "Age": [25, 30] }) df2 = pd.DataFrame({ "Name": ["Charlie", "David"], "Age": [35, 40] }) # Concatenate vertically (axis=0) result = pd.concat([df1, df2], axis=0) print(result)
copy
1234567891011121314
# Create two DataFrames with different columns df1 = pd.DataFrame({ "A": [1, 2], "B": [3, 4] }) df2 = pd.DataFrame({ "C": [5, 6], "D": [7, 8] }) # Concatenate horizontally (axis=1) result = pd.concat([df1, df2], axis=1) print(result)
copy

The ignore_index parameter in concat() determines whether to reset the row index in the resulting DataFrame. When set to True, the index will be renumbered from 0, which is helpful if you do not want to keep the original indices from the source DataFrames. The keys parameter allows you to add a hierarchical index (MultiIndex) to the result, labeling each block of the concatenated DataFrame with a key. This is useful for tracking the origin of each row after concatenation, especially when combining data from multiple sources.

question mark

Which of the following best describes the difference between concatenating DataFrames along axis=0 and axis=1 using concat()?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 29

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 1. Capítulo 29
some-alt