如何提取指定列的子DataFrame并追加额外数据行?
实现方案
方法一:用pd.concat拼接新行(兼容新版pandas)
这是通用性最强的写法,适配pandas各个版本,步骤清晰:
- 先提取原表的
start_time和quantity_start列作为基础结果 - 从原表最后一行取出
end_time和quantity_end,构造单行DataFrame - 用
pd.concat拼接两个表,可选重置索引保证序号连续
import pandas as pd # 构造示例数据 df = pd.DataFrame({ 'start_time': [0, 10, 20.], 'end_time': [10, 20, 30], 'quantity_start': [0, 1, 3], 'quantity_end': [1, 3, 10] }) # 提取基础子表 result = df[['start_time', 'quantity_start']].copy() # 构造需要追加的最后一行 last_row = pd.DataFrame({ 'start_time': [df['end_time'].iloc[-1]], 'quantity_start': [df['quantity_end'].iloc[-1]] }) # 拼接并重置索引 result = pd.concat([result, last_row], ignore_index=True) print(result)
方法二:直接用loc追加行(代码最简洁)
适合小数据量场景,一行代码完成追加操作:
result = df[['start_time', 'quantity_start']].copy() # 直接在结果末尾插入新行 result.loc[len(result)] = [df['end_time'].iloc[-1], df['quantity_end'].iloc[-1]] print(result)
方法三:构造Series拼接(大数据量最优)
如果处理百万级以上的大表,这种方式能避免DataFrame拼接的性能开销:
# 合并原start_time列和最后一个end_time值 new_start = pd.concat([df['start_time'], pd.Series([df['end_time'].iloc[-1]])], ignore_index=True) # 合并原quantity_start列和最后一个quantity_end值 new_quantity = pd.concat([df['quantity_start'], pd.Series([df['quantity_end'].iloc[-1]])], ignore_index=True) # 生成最终结果表 result = pd.DataFrame({'start_time': new_start, 'quantity_start': new_quantity}) print(result)
场景建议
- 日常小数据量用方法二,代码最简洁;
- 大数据量处理选方法三,性能更优;
- 需要兼容不同pandas版本时用方法一,稳定性最强。
内容的提问来源于stack exchange,提问作者24n8
相关产品推荐
相关产品推荐

