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

求助:pandas中为iloc提取的单列DataFrame指定列名后无法识别

问题原因与解决方法

问题根源

你用df.iloc[:,4]提取单列时,得到的是pandas Series对象,而非DataFrame。Series没有columns属性,直接赋值new_df.columns = ["EMP_ID"]不会生效,所以后续调用列名会报错。

解决方法

以下三种方法都能解决这个问题:

  1. 提取时直接保留DataFrame格式
    使用双层方括号提取,确保返回的是DataFrame:
new_df = df.iloc[:, [4]]  # 注意这里是[4],不是4
new_df.columns = ["EMP_ID"]
  1. 将Series转为DataFrame时指定列名
    如果已经得到了Series,直接用to_frame()方法转换并指定列名:
# 假设new_df是之前用iloc[:,4]得到的Series
new_df = new_df.to_frame(name="EMP_ID")
  1. 提取时直接重命名列
    一步完成提取和重命名,无需后续操作:
new_df = df.iloc[:, [4]].rename(columns={df.columns[4]: "EMP_ID"})

验证

完成上述操作后,执行print(new_df['EMP_ID'])就能正常输出数据,和其他DataFrame合并时也不会触发KeyError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:52:11