I started to work with pandas very recently, and my issue is the following: I have two loops, that generates each 10 values. What I want to do is to insert at the bottom of my data frame the generated values, in such a way that the index is the same for both loops.
Here is a mock-up example, that is quite close of what I'm trying to do:
import pandas as pd
import random
randint = {'rand': [10,52,99,8],'rand2': [541,632,789,251], 'rand3': [1,3,4,1]}
df = pd.DataFrame(randint, columns = ['rand','rand2', "rand3"])
i = j = len(df)
for x in range(10):
rand = random.randint(1,101)
rand2 = random.randint(1,1001)
df.loc[df.index[i], "rand"] = rand
df.loc[df.index[i], "rand2"] = rand2
i = i + 1
for y in range(10):
rand3 = random.randint(1,11)
df.loc[df.index[j], "rand3"] = rand3
j = j + 1
print(df)
So, what I would like is to have for instance at row 5 the first set of rand, rand2, rand3 at the same row, and so forth (e.g.: for x and y = 1, I would have the three values at the same row, for x and y = 2, same thing, etc...). The issue is that I have read that it was not a good idea to iterate with pandas (and obviously, pandas is raising me the error "index 4 is out of bounds for axis 0 with size 4"), but I really have trouble to understand the pandas syntax and I'm a bit lost on how I am supposed to tackle this issue. Thank you for your help.
Expected output:
At first, my dataframe would look like this:
rand | rand2 | rand3 |
---|---|---|
10 | 541 | 1 |
52 | 632 | 3 |
99 | 789 | 4 |
8 | 251 | 1 |
Now, let us imagine that the first time in the first loop (so for x = 1) , rand = 8, rand2 = 455, and for the first time of the second loop (so for y=1), rand3 = 7.
So now, I would like to add the values obtained to the last row, in such a way that my dataframe would look like this:
rand | rand2 | rand3 |
---|---|---|
10 | 541 | 1 |
52 | 632 | 3 |
99 | 789 | 4 |
8 | 251 | 1 |
8 | 455 | 7 |
The issue is that I don't really know to indicate to pandas that I want to have the same index for the two loops. Let me know if it is still not clear.