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

如何用Python Pandas实现两行相减并转换为列表格式?

报错核心原因
  • 直接使用df[整数]语法时,Pandas默认匹配列名,你没有名称为1、96的列,因此触发KeyError
  • df[96,:]不是Pandas的合法索引语法,按行的位置索引需要使用iloc属性
实现代码
import pandas as pd
from datetime import datetime

# 读取源CSV
df = pd.read_csv('your_file.csv')

# 按位置取行:iloc[0]为表头后第一行,iloc[-1]为最后一行,相减后转列表
diff_res = (df.iloc[-1] - df.iloc[0]).tolist()

# 替换第一个元素为当前日期,日期格式可自定义
diff_res[0] = datetime.now().strftime('%Y-%m-%d')

# 追加到目标文件,使用csv模块写入单行更便捷
import csv
with open('result.csv', 'a', encoding='utf-8', newline='') as f:
    csv.writer(f).writerow(diff_res)
可选调整说明
  • 若需固定取第96行(表头后第97行)而非最后一行,将df.iloc[-1]替换为df.iloc[96]即可
  • 若使用Pandas方法追加,可使用如下写法,无需额外导入csv模块:
pd.DataFrame([diff_res]).to_csv('result.csv', mode='a', header=False, index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:06:04