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

如何将长度为365的列表循环拆分为多个Pandas DataFrame

Convert List Elements to Individual Pandas DataFrames via Loop

Got it, let's work through this. You've got a list d with 365 elements, each holding table-like data (with columns like No, Name and their corresponding rows), and you want to automate converting each element into its own Pandas DataFrame (like df1 for d[1]). Here are two practical approaches:

First, a quick note on indexing

Python lists use 0-indexing, so your 365-element list runs from d[0] (first element) to d[364] (last). If you specifically want df1 to map to d[1], double-check that your list has enough elements (or adjust the code below to map df1 to d[0]—that's more aligned with Python's default behavior).


If you really need separate variables like df1, df2, etc., you can use Python's globals() function to dynamically create them. Just keep in mind: managing 365 separate variables will get messy fast.

import pandas as pd

# Loop through the list and create df1, df2...df365
for idx in range(1, len(d) + 1):
    # Map df1 to d[0], df2 to d[1], etc.
    # To map df1 to d[1], replace d[idx-1] with d[idx] (ensure idx doesn't exceed len(d)-1)
    globals()[f"df{idx}"] = pd.DataFrame(d[idx-1])

This is the cleaner, more maintainable option. Instead of scattering variables everywhere, you'll store all DataFrames in a single dictionary where keys are names like df1 and values are the corresponding DataFrames.

import pandas as pd

# Initialize an empty dictionary to hold your DataFrames
dfs_dict = {}

# Populate the dictionary
for idx in range(1, len(d) + 1):
    dfs_dict[f"df{idx}"] = pd.DataFrame(d[idx-1])

# Access individual DataFrames like this:
# dfs_dict["df1"]  # Gets the DataFrame from d[0]
# dfs_dict["df365"]  # Gets the DataFrame from d[364]

Bonus: If your elements are raw text tables

If the elements in d are string-formatted tables (not already structured data like lists of dictionaries), you can parse them using StringIO to read them as CSV-like data:

from io import StringIO

for idx in range(1, len(d) + 1):
    # Example: d[idx-1] is a string like "No,Name\n1,Alice\n2,Bob"
    dfs_dict[f"df{idx}"] = pd.read_csv(StringIO(d[idx-1]))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:14:33