如何将长度为365的列表循环拆分为多个Pandas DataFrame
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).
Approach 1: Create individual DataFrame variables (not recommended for large sets)
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])
Approach 2: Store DataFrames in a dictionary (highly recommended)
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

