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

Pandas用groupby.get_group提取多Keycode值合并为DataFrame失败如何解决

问题原因
  • append() 方法不会修改原DataFrame对象,而是返回一个合并后的新DataFrame,你没有将append执行后的结果赋值给变量,所以原变量onetwofive始终仅保留Keycode为125的内容。
  • 这类简单筛选需求不需要用groupby实现,直接用布尔索引性能更高、写法更简洁。
正确修改方式

方法1:调整原有代码逻辑

将append返回的结果重新赋值给变量即可:

groups = df.groupby(df.Keycode) # Keycode is the column label I grouped on
onetwofive = groups.get_group('125') # 125 is the column value I'm wanting to pull out
onetwofive = onetwofive.append(groups.get_group('175'))  # 175 is the column value I'm wanting to pull out and append with the 125 group

注意:pandas 2.0及以上版本已经正式弃用append方法,更推荐使用pd.concat做DataFrame合并

方法2:推荐写法(布尔索引一步完成)

不需要分组操作,直接筛选符合条件的所有行即可:

# Keycode列为字符串类型时用这个写法
result = df[df['Keycode'].isin(['125', '175'])]

# Keycode列为数值类型时用这个写法
# result = df[df['Keycode'].isin([125, 175])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:54:03