Python实现每次运行生成的DataFrame追加为时间序列数据
解决方案
核心思路
在函数外部维护一个全局的目标DataFrame,每次调用Vega_dict()获取新的单行数据后,将其追加到这个目标DataFrame中,最终形成时间序列数据。
具体实现步骤
初始化目标DataFrame
先创建一个和Vega_dict()返回结构一致的空DataFrame,用于存储历史数据:import pandas as pd # 初始化存储时间序列的目标DataFrame target_time_series = pd.DataFrame(columns=["Time", "Sum of OTM CE", "Sum of OTM PE"])优化原函数(可选但更简洁)
原函数通过列表转置生成DataFrame的写法可以简化,直接用字典构造单行DataFrame:def Vega_dict(): Sum_CE_Vega = Final_df.loc[Final_df['instrumentType'] == 'CE', 'vega'].sum() Sum_PE_Vega = Final_df.loc[Final_df['instrumentType'] == 'PE', 'vega'].sum() # 直接构造单行DataFrame,避免转置操作 return pd.DataFrame({ "Time": [Time], "Sum of OTM CE": [Sum_CE_Vega], "Sum of OTM PE": [Sum_PE_Vega] })每次运行追加数据
每次调用函数获取新数据后,用pd.concat()将其追加到目标DataFrame中(设置ignore_index=True重置索引,避免重复索引问题):# 获取本次运行的新数据 new_row = Vega_dict() # 追加到目标时间序列DataFrame target_time_series = pd.concat([target_time_series, new_row], ignore_index=True)
效果演示
- 第一次运行后
target_time_series:Time Sum of OTM CE Sum of OTM PE 0 21:43:53 163.835972 154.28453 - 第二次运行后
target_time_series:Time Sum of OTM CE Sum of OTM PE 0 21:43:53 163.835972 154.28453 1 21:43:59 x2_value y2_value
注意事项
- 确保
Final_df和Time变量在调用Vega_dict()时是已定义且有效的外部变量。 - 不要在
Vega_dict()函数内部初始化目标DataFrame,否则每次调用都会重置数据。
内容的提问来源于stack exchange,提问作者denise
相关产品推荐
相关产品推荐

