I'm writetwo python dataframe columns so that two coordinates, X and Y, will increment down their respective columns. For example:
| X | Y |
|:----|----:|
| 0 | 0 |
| 0 | 1 |
| 0 | 2 |
| 0 | 3 |
| 0 | 4 |
| 1 | 0 |
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 0 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 2 | 4 |
| ... | ... |
Any ideas how to generate these columns?
CodePudding user response:
You can generate dictionary with iteration and then create DataFrame from that you can check below sample for that;
import pandas as pd
my_df = []
for i in range(0,10):
d = {
'x' : i, # some formula for obtaining values
'y' : i*2,
}
my_df.append(d)
my_df = pd.DataFrame(my_df)
print(my_df)
To generate values you require you need to fiddle with iteration. Leaving up to you :). Logic would be this, you need to add (0,1,2,3,4) values to y column, so you can get modulo each iteration and add accordingly. For x column you need to 1 to x value after each 4th iteration.
CodePudding user response:
Just use range()
and a list comprehension (modify the 3
if you want another length):
df = pd.DataFrame(
[[n, m] for n in range(3) for m in range(5)],
columns = ["X", "Y"]
)
Result:
X Y
0 0 0
1 0 1
2 0 2
3 0 3
4 0 4
5 1 0
6 1 1
7 1 2
8 1 3
9 1 4
10 2 0
11 2 1
12 2 2
13 2 3
14 2 4
Or use itertools.product
to get the same result:
from itertools import product
df = pd.DataFrame(product(range(3), range(5)), columns = ["X", "Y"])