如何通过循环基于已有DataFrame生成新DataFrame并合并?
Solution
Got it, here's a straightforward way to loop through generating those modified DataFrames and combine them all into one big dataset:
Approach
- Start by storing all your DataFrames in a list, beginning with your original
df. - For each new DataFrame you want to create, take the most recent one from the list, apply your modification rules (multiply avgTemp by tempchange, add 20 to year), and add it to the list.
- Once all copies are generated, concatenate everything into a single DataFrame.
Code Implementation
import pandas as pd # Configure your parameters here num_additional_dfs = 3 # Number of new DataFrames to generate (df2, df3, df4) # tempchange = your existing temperature multiplier (e.g., ~1.07 from your sample) # Initialize list with original DataFrame df_list = [df] for _ in range(num_additional_dfs): # Get the last modified DataFrame to base the next one on last_df = df_list[-1] # Create a copy to avoid altering the original new_df = last_df.copy() # Apply your calculation logic new_df['avgTemp'] = new_df['avgTemp'] * tempchange new_df['year'] = new_df['year'] + 20 # Add the new DataFrame to our collection df_list.append(new_df) # Combine all DataFrames into the final dataset df_final = pd.concat(df_list)
How It Works
Let's use your sample data to illustrate:
- Starting with
df(year 2012), the first loop createsdf2(year 2032, avgTemp scaled by tempchange) - The second iteration takes
df2to makedf3(year 2052, avgTemp scaled again) - The third iteration generates
df4(year 2072, avgTemp scaled once more) - The final
df_finalwill have all these rows stacked, matching your sample output but with as many additional years as you specify.
Optional Variation
If you want each new DataFrame to be based on the original df instead of the previous modified one (e.g., each year uses the original temp multiplied by tempchange raised to the power of the iteration count), just replace last_df with df inside the loop. But based on your question, building on the prior modified DataFrame is exactly what you need.
内容的提问来源于stack exchange,提问作者Timo
相关产品推荐
相关产品推荐

