如何在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
- Incorrect global variable syntax: You can't combine
globaland assignment in a single line (global df = pd.DataFrame(...)). Module-level variables are already global by default—just assign directly. - Missing global declaration in the function: When modifying a global variable inside a function, you need to explicitly declare
global dffirst. Without this, Python will treatdfas a local variable, triggering anUnboundLocalError. - Hardcoded string instead of variable: You used
'timestamp1'(a literal string) instead of the actual variabletimestamp1, so you were storing text instead of the generated timestamp. - Outdated
appendmethod: Pandas deprecateddf.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
dfdirectly—noglobalkeyword needed here. Inside functiona(),global dftells 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.concatis a more robust alternative. - Variable reference: We removed the quotes around
timestamp1so 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
相关产品推荐
相关产品推荐

