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

如何在Python函数中追加全局DataFrame且不传递参数?

Fixing Global DataFrame Appending Issue

Let's work through the problems in your code and get it working so you can append rows to the global DataFrame without passing any parameters:

Key Issues in Your Original Code

  1. Incorrect global variable syntax: You can't combine global and assignment in a single line (global df = pd.DataFrame(...)). Module-level variables are already global by default—just assign directly.
  2. Missing global declaration in the function: When modifying a global variable inside a function, you need to explicitly declare global df first. Without this, Python will treat df as a local variable, triggering an UnboundLocalError.
  3. Hardcoded string instead of variable: You used 'timestamp1' (a literal string) instead of the actual variable timestamp1, so you were storing text instead of the generated timestamp.
  4. Outdated append method: Pandas deprecated df.append() in version 2.0+, so we'll use a more modern, supported approach to add rows.

Corrected Full Code

import pandas as pd
import datetime

# Initialize global DataFrame (module-level variables are global by default)
df = pd.DataFrame(columns=['Time', 'Call'])

def a():
    # Declare we're modifying the global df variable
    global df
    
    now = datetime.datetime.now()
    timestamp1 = now.strftime("%Y-%m-%d %H:%M:%S")
    call_num = 1
    
    # Modern way to add a single row to the end
    df.loc[len(df)] = {'Time': timestamp1, 'Call': call_num}
    
    # Alternative: Use pd.concat for better compatibility (great for batch rows)
    # new_row = pd.DataFrame({'Time': [timestamp1], 'Call': [call_num]})
    # df = pd.concat([df, new_row], ignore_index=True)

def main():
    a()
    print("First entry added")
    a()
    print("Second entry added")
    # Print the final DataFrame to verify results
    print(df)

main()

Breakdown of the Fixes

  • Global variable handling: At the module level, we just create df directly—no global keyword needed here. Inside function a(), global df tells Python we want to modify the existing global variable instead of creating a new local one.
  • Row addition: df.loc[len(df)] adds a new row at the end of the DataFrame in a clean, efficient way. If you need to add multiple rows at once, pd.concat is a more robust alternative.
  • Variable reference: We removed the quotes around timestamp1 so we're using the actual generated timestamp value instead of the text "timestamp1".

When you run this code, you'll see two rows added to the global DataFrame with the correct timestamps each time a() is called.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:02:57