-1

python_3 question: Does anyone can help me write this codes in a for loop:

df_0 = df[0:100]
df_1 = df[100:200]
df_2 = df[200:300]
.
.
df_n = df[n*100:len(df.index)]
Sway Wu
  • 379
  • 3
  • 8
  • Can you please provide us what you have tried ? This is not a good way for asking someone to help you, you should at least give it a shot and try to do it yourself. – BcK Jan 03 '20 at 20:23
  • I know you want to create separate variables for each slice but another option would be to create a single dictionary that contains everything that you could then select from/iterate through: ```{f'df_{i}': df[n:(n+100)] for i,n in enumerate(range(0, len(df), 100))}``` – eva-vw Jan 03 '20 at 20:23

1 Answers1

1

You can try this,

for i in range(0, len(df) + 1, 100):
    locals()[f'df_{int(i / 100)}'] = df[i: i + 100]

print(df_0)
print(df_1)

But before using the locals() method, it may be useful to read: https://stackoverflow.com/a/24197790/8205554

And I agree with eva-vw's comment. It would be a better option.

E. Zeytinci
  • 2,642
  • 1
  • 20
  • 37
  • Hi @Sway Wu if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this – E. Zeytinci Jan 10 '20 at 20:11