I want to spin multiple dataframes with a for statement

Asked 2 years ago, Updated 2 years ago, 266 views

df_1,df_2,df_3 and all columns are the same.

df_1['year'].shape
df_2['year'].shape
df_3['year'].shape

You want to spin the above with the for statement,

for in (1,2,3):
    df_(i)['year'].shape

I'd like to do this, but how can I automate it?

python python3 pandas numpy matplotlib

2022-09-30 21:49

1 Answers

You can do it using eval as shown in the following code:

for in (1,2,3):
    event("df_"+str(i)+"['year'].shape")

eval is the last resort when there is no other way.
I think it's better to write like the following code.

for dfin [df_1, df_2, df_3]:
    df['year'].shape

If you really want to specify a data frame by number, you can make a list in advance.

df_list=[df_1, df_2, df_3]
for in (1, 2, 3):
    (df_list[i-1])['year'].shape

As Kunif commented, df['year'].shape alone is meaningless.I interpreted it as just an example.


2022-09-30 21:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.