如何不使用concat向DataFrame的索引0位置添加字典生成的行?
不用concat实现向DataFrame开头插入指定行的方法
你当前的代码通过创建临时DataFrame再用concat拼接,实现了把字典首个键作为names值的行插入到原DataFrame的索引0位置。下面提供两种不用concat的实现方式:
方法一:利用loc直接插入行
可以通过调整原DataFrame的索引,直接在索引0位置插入新行,步骤如下:
- 先将原DataFrame的索引整体加1,空出索引0的位置
- 直接给索引0赋值新行数据
- 最后可选择重置索引,以获得连续的整数索引
代码示例:
import pandas as pd df = pd.DataFrame({ "names": ["a", "a", "a"], "org_names": ["a", "a", "a"], "math" : ["!not_div", "=", "*"], "values": [1, 2, 3], "end_result" : ["", 1,2] }) data = {"interception": 1, "a": 2, "b": 3, "c": 5, "d": 6 } # 原索引向后偏移1,空出索引0 df.index = df.index + 1 # 插入新行到索引0 df.loc[0] = [list(data.keys())[0], "", "", "", 1] # 按索引排序并重置索引,恢复连续顺序 df = df.sort_index().reset_index(drop=True) print(df)
输出结果:
names org_names math values end_result 0 interception 1 1 a a !not_div 1 2 a a = 2 1 3 a a * 3 2
方法二:使用append方法(注意版本兼容性)
在pandas 1.x版本中,可直接用append方法把单行数据追加到开头,需要先构造Series对象并设置ignore_index=True来重新生成索引:
代码示例:
import pandas as pd df = pd.DataFrame({ "names": ["a", "a", "a"], "org_names": ["a", "a", "a"], "math" : ["!not_div", "=", "*"], "values": [1, 2, 3], "end_result" : ["", 1,2] }) data = {"interception": 1, "a": 2, "b": 3, "c": 5, "d": 6 } # 构造匹配原DataFrame列名的Series new_row = pd.Series({ "names": list(data.keys())[0], "org_names": "", "math" : "", "values": "", "end_result" : 1, }) # 将新行放在前面,append后重置索引 new_df = pd.DataFrame([new_row]).append(df, ignore_index=True) print(new_df)
输出结果与方法一一致。注意:pandas 2.0及以上版本已移除append方法,高版本用户建议优先使用方法一。
方法对比
loc插入方式更高效,无需额外创建临时DataFrame,可直接在原数据上操作,适合数据量较大的场景。append写法更简洁,但受限于pandas版本,本质也是创建新对象,性能和concat差异不大。
内容的提问来源于stack exchange,提问作者shaftel
相关产品推荐
相关产品推荐

