Home > front end >  Slicing a DataFrame and assign it to new variables with a "for" loop
Slicing a DataFrame and assign it to new variables with a "for" loop

Time:01-28

I have a dataframe (2025x10) . I want to slice the dataframe and assign it to a new DataFrame variables that each variable contained with 25 rows consecutively with the respect of the index. So there will be 81 new DataFrame variables ( 2025:25 = 81) Here is the code that I wrote manually without a "for" loop

newdata_1 =old_data.iloc[0:25,:]
newdata_2=old_data.iloc[25:50,:]
newdata_3 =old_data.iloc[50:75,:]
newdata_4=old_data.iloc[75:100,:]
#until newdata_81=old_data.iloc[2000:2025,:]

Can I do that with a single "for" loop instead of writing the whole code manually?

CodePudding user response:

What you want is to create new variables dynamically with globals() or locals() (or vars()). It's not a very good practice but as you control variable names, it's not so dangerous.

old_data = pd.DataFrame({'A': np.random.random(2025)})

for i, df in enumerate(np.array_split(old_data, len(old_data) / 25), 1):
    globals()[f'newdata_{i}'] = df

Now you can access your slice with new variable names:

>>> newdata_45
             A
1100  0.443526
1101  0.564314
1102  0.548801
1103  0.561671
1104  0.668331
1105  0.046114
1106  0.090302
1107  0.830096
1108  0.991514
1109  0.285102
1110  0.093784
1111  0.535805
1112  0.154352
1113  0.678095
1114  0.284844
1115  0.137232
1116  0.219372
1117  0.816656
1118  0.519414
1119  0.673969
1120  0.674139
1121  0.239825
1122  0.257405
1123  0.565221
1124  0.561289

CodePudding user response:

all_df = {}
for i, j in enumerate(range(0, 2025, 25)):
    all_df[f"newdata_{i 1}"] = df.iloc[j:j 25,:]
  •  Tags:  
  • Related