You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于条件为带命名索引的Pandas DataFrame插入新行

解决Pandas命名索引DataFrame添加新行的问题

嘿,我明白你遇到的困扰了——你的DataFrame已经把system_call设为命名索引,之前用df.loc[-1]的方法只适用于默认的整数位置索引,所以没法正确添加新行。下面给你几种适配命名索引的解决方案:

1. 直接通过新索引值添加单行

因为你的索引是system_call的具体值,所以添加新行时,直接把新的system_call值作为loc的索引键就行,比如要添加你期望输出里的futex行:

# 假设words是存储新行数据的列表,比如words = ['futex', 13, 6]
df.loc[words[0]] = [words[1], words[2]]

这样就能直接把futex作为新索引,对应的frequency和file_frequency值也会被正确赋值。

2. 结合if-else条件判断(推荐)

如果需要先判断该system_call是否已存在,再决定是添加新行还是更新现有行,可以这么写:

words = ['futex', 13, 6]  # 示例新数据
if words[0] not in df.index:
    # 不存在则添加新行
    df.loc[words[0]] = [words[1], words[2]]
else:
    # 已存在则更新对应数值(比如累加频率,根据你的需求调整)
    df.loc[words[0], 'frequency'] += words[1]
    df.loc[words[0], 'file_frequency'] += words[2]

3. 批量添加多行(可选)

如果需要一次性添加多个新行,推荐用pd.concat(新版本Pandas已弃用append方法):

# 构造包含新行的DataFrame,索引为新的system_call值
new_rows = pd.DataFrame(
    {'frequency': [13, 99], 'file_frequency': [6, 3]},
    index=['futex', 'new_syscall']
)
# 合并到原DataFrame
df = pd.concat([df, new_rows])

执行完上述操作后,你的DataFrame就会包含期望的新行,输出和你给出的示例一致啦~

内容的提问来源于stack exchange,提问作者ubuntu_noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:39:46