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

如何使用for循环创建n个空的pandas DataFrame?

Hey there! Let's get this sorted for you. The issue with your original code is that df(i) = pd.DataFrame() isn't valid Python syntax—parentheses here are used for function calls, not assigning variables. Here are two approaches to create those named empty DataFrames:

推荐方案:用字典存储(更易管理)

This is the cleaner, more maintainable option because it keeps all your DataFrames organized in one place, avoiding messy global variables and potential naming conflicts.

import pandas as pd
n = 6
# Create an empty dictionary to hold your DataFrames
df_dict = {}

# Loop from 1 to n (since you want df1, df2...dfn)
for i in range(1, n + 1):
    df_dict[f'df{i}'] = pd.DataFrame()

# Access your DataFrames like this:
print(df_dict['df1'])  # Prints the empty df1

Why this works: We're using a dictionary where each key is the name you want (like 'df1') and the value is the empty DataFrame. Later, if you need to iterate over all your DataFrames or modify them in bulk, you can loop through the dictionary easily.

可选方案:动态创建全局变量(直接生成df1、df2等)

If you really need the DataFrames to be standalone variables (like df1, df2 instead of accessing them via a dictionary), you can use Python's globals() function. Note: This is generally not recommended because it clogs up your namespace, makes debugging harder, and can cause unexpected issues if variable names overlap.

import pandas as pd
n = 6

for i in range(1, n + 1):
    # Dynamically create a global variable named df1, df2...dfn
    globals()[f'df{i}'] = pd.DataFrame()

# Now you can use them directly:
print(df3)  # Prints the empty df3

Just keep in mind that this approach is less scalable and harder to track as your code grows. Stick with the dictionary method unless you have a specific reason not to!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 22:53:12