LeetCode 题解工作台
重塑数据:连结
DataFrame df1 +-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +---------…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Reshape Data: Concatenate core interview pattern
答案摘要
import pandas as pd def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Reshape Data: Concatenate core interview pattern 题型思路
题目描述
DataFramedf1+-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +-------------+--------+ DataFramedf2+-------------+--------+ | Column Name | Type | +-------------+--------+ | student_id | int | | name | object | | age | int | +-------------+--------+
编写一个解决方案,将两个 DataFrames 垂直 连接成一个 DataFrame。
结果格式如下示例所示。
示例 1:
输入: df1 +------------+---------+-----+ | student_id | name | age | +------------+---------+-----+ | 1 | Mason | 8 | | 2 | Ava | 6 | | 3 | Taylor | 15 | | 4 | Georgia | 17 | +------------+---------+-----+ df2 +------------+------+-----+ | student_id | name | age | +------------+------+-----+ | 5 | Leo | 7 | | 6 | Alex | 7 | +------------+------+-----+ 输出: +------------+---------+-----+ | student_id | name | age | +------------+---------+-----+ | 1 | Mason | 8 | | 2 | Ava | 6 | | 3 | Taylor | 15 | | 4 | Georgia | 17 | | 5 | Leo | 7 | | 6 | Alex | 7 | +------------+---------+-----+ 解释: 两个 DataFrame 被垂直堆叠,它们的行被合并。
解题思路
方法一
import pandas as pd
def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame:
return pd.concat([df1, df2], ignore_index=True)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the number of rows in both DataFrames since each row is copied into the new DataFrame. Space complexity is proportional to the total number of rows, as a new DataFrame is created to hold the combined data. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on handling vertical stacking of DataFrames and preserving column integrity.
- question_mark
Watch for misaligned columns that can introduce NaN values in the concatenated result.
- question_mark
Be ready to explain index handling and why reset_index may be necessary after concatenation.
常见陷阱
外企场景- error
Concatenating DataFrames with mismatched columns produces unexpected NaN entries.
- error
Forgetting to set axis=0 in pandas.concat can produce horizontal concatenation instead of vertical.
- error
Not resetting the index can leave duplicate indices that break later DataFrame operations.
进阶变体
外企场景- arrow_right_alt
Concatenate more than two DataFrames at once using a list in pandas.concat.
- arrow_right_alt
Perform concatenation with additional keys to create hierarchical indexing for source tracking.
- arrow_right_alt
Concatenate DataFrames with different column orders by reindexing before merging to ensure alignment.