Python Forum
How to upload dfs using for loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to upload dfs using for loop?
#1
Hi, I have a following problem. I would like to define new data frames using a for loop. I have a big dataframe df that contains values from all 6 rounds. I need to have df1, df2, df3, ... ,df6 that will contain only values from round 1, 2, .., 6 respectively.

I tried this:

x = {}

for i in range(1, 6):
    x[i] = df.loc[df['round'] == i]
    name = "df" + str(i)
    print(name)
    name = x[i]
I got a dictionary X that contains 6 dataframes. But how can I upload them into my environment and name them df1, df2, df3, ... ,df6 ? Thanks a lot!
Reply
#2
Reason you are not doing this:
df1 = df.loc[df['round'] == 1]
df2 = df.loc[df['round'] == 2]
df3 = df.loc[df['round'] == 3]
df4 = df.loc[df['round'] == 4]
df5 = df.loc[df['round'] == 5]
df6 = df.loc[df['round'] == 6]
Personally, I would prefer to work with a list of dataframes
Reply
#3
Thanks for reply!

Yes, I am not doing this:
df1 = df.loc[df['round'] == 1]
df2 = df.loc[df['round'] == 2]
df3 = df.loc[df['round'] == 3]
df4 = df.loc[df['round'] == 4]
df5 = df.loc[df['round'] == 5]
df6 = df.loc[df['round'] == 6]
But why? And how can I load dataframes using a list of dataframes, please?
Reply
#4
(Nov-10-2020, 04:58 PM)rama27 Wrote: I need to have df1, df2, df3, ... ,df6
name them df1, df2, df3, ... ,df6 ?

I would recommend to start with thinking about WHY do you need to name them? WHY do you need separate variables and not datastructure?

For thought food I recommend to read:

- Keep data out of your variable names

Quote:The thing all these have in common is trying to bridge the gap between two domains: the data in your program, and the names of data in your program. Any time this happens, it’s a clear sign that you need to move up a level in your data modeling. Instead of 26 lists, you need one dictionary. Instead of N tables, you should have one table, with one more column in it.

- Why you don't want to dynamically create variables

Quote:but if you think you need it, your first step should be to make sure you really do, and your second step should be to make doubly sure.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
Thanks for reply, but I am afraid that your solution is not suitable for my case. I need to load dfs separately, exactly how I write.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020