Reputation: 306
In Python, I would like to create a dataset composed of 3 columns containing RGB colors:
R G B
0 0 0 0
1 0 0 8
2 0 0 16
3 0 0 24
...
31 0 0 248
32 0 8 0
33 0 8 8
...
Of course, I could use 3 nested for-loops, but I wonder if there is not a more optimal solution.
for R in range(0,255,8):
for G in range(0,255,8):
for B in range(0,255,8):
# ... Do something here
Upvotes: 1
Views: 4856
Reputation: 5237
You can generate the RGB color codes using a list comprehension, then pass that to pandas.DataFrame
to put it into a DataFrame
.
import pandas as pd
l = range(0, 255, 8)
rgb = [[r, g, b] for r in l for g in l for b in l]
df = pd.DataFrame(rgb, columns=['R', 'G', 'B'])
print(df)
Output:
R G B
0 0 0 0
1 0 0 8
2 0 0 16
3 0 0 24
4 0 0 32
... ... ... ...
32763 248 248 216
32764 248 248 224
32765 248 248 232
32766 248 248 240
32767 248 248 248
[32768 rows x 3 columns]
Though using the range range(0, 255, 8)
will end at 248, so if you want to end at 255, then use range(0, 257, 8)
instead.
Upvotes: 1
Reputation: 3121
You can do it using itertool.product()
.
import itertools
it = itertools.product(range(0, 255, 8), range(0, 255, 8), range(0, 255, 8))
The result is huge that's why I am putting it at 10 values.
print(list(it)[:10])
# Output
# [(0, 0, 0), (0, 0, 8), (0, 0, 16), (0, 0, 24), (0, 0, 32),
# (0, 0, 40), (0, 0, 48), (0, 0, 56), (0, 0, 64), (0, 0, 72)]
Upvotes: 1