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

如何在Pandas DataFrame中追加新值并保存到CSV?代码问题求助

问题排查与解决方案

核心问题

你的代码无法写入CSV的原因是:初始化的trade是空DataFrame,直接给列赋值不会生成有效数据行。空DataFrame没有可写入的行记录,调用to_csv时自然不会输出任何内容。

修复方案(两种可选)

方案1:直接构造单条交易记录的DataFrame

这种方式更简洁,避免空DataFrame的赋值问题:

import pandas as pd
import datetime
import os

columns = ["Datetime","Symbol","Trade_price","Trade_type"]

if buy_condition:  # 简化条件判断,无需写==True
    ce_changepos(ce_df, exch, buy=True)
    # 合并时间处理代码
    current_time = datetime.datetime.today().replace(microsecond=0)
    # 直接构造包含当前交易数据的DataFrame
    trade_record = pd.DataFrame([{
        "Datetime": str(current_time),
        "Symbol": ceSymbol,
        "Trade_price": ce_df['sp1'].iloc[-1],
        "Trade_type": "CE Buy"
    }], columns=columns)
    
    # 用os.path.join避免路径拼接错误
    file_path = os.path.join(path, 'trade.csv')
    # 判断文件是否存在,首次写入才加表头
    file_exists = os.path.isfile(file_path)
    trade_record.to_csv(file_path, mode='a', header=not file_exists, index=False)
    
    print(f"Buy order placed for {ceSymbol}")   
else:
    print(f"CE buy condition for {ceSymbol} not fulfilled")

方案2:给空DataFrame添加行后再写入

如果你习惯保留初始化空DataFrame的逻辑,可以用loc在末尾添加行:

import pandas as pd
import datetime
import os

columns = ["Datetime","Symbol","Trade_price","Trade_type"]
trade = pd.DataFrame(columns=columns)

if buy_condition:
    ce_changepos(ce_df, exch, buy=True)
    current_time = datetime.datetime.today().replace(microsecond=0)
    # 通过loc给空DataFrame添加一行数据
    trade.loc[len(trade)] = [str(current_time), ceSymbol, ce_df['sp1'].iloc[-1], "CE Buy"]
    
    file_path = os.path.join(path, 'trade.csv')
    file_exists = os.path.isfile(file_path)
    trade.to_csv(file_path, mode='a', header=not file_exists, index=False)
    
    print(f"Buy order placed for {ceSymbol}")   
else:
    print(f"CE buy condition for {ceSymbol} not fulfilled")

额外优化点

  • 用os.path.join(path, 'trade.csv')替代直接拼接字符串,避免因path末尾无斜杠导致的路径错误(比如path="./data"会变成./datatrade.csv)。
  • 新增文件存在判断逻辑,确保只有第一次创建文件时写入表头,后续追加数据时不会重复写表头。
  • 简化buy_condition == True为buy_condition,符合Python代码风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:24:26