Forum Discussion
ValeriaBreve
Post Partisan
3 years agoAssign attributes randomly
Hello, I have a product table in PowerQuery with Product Names (~1500 unique), and another table that contains a color scheme that I would like to implement for the products (tableau20, so 20 colors...
- 3 years ago
ValeriaBreve I have split the code intor variables/step and commented the code so that it is easy to understand:
Table.AddColumn ( Source, "Color", each let /* Get the Color Column as a list You can also use List.Buffer in case the code is slow ColorList = List.Buffer ( Colors[Color] ) */ ColorList = Colors[Color], // Count the colors, returns 16 in my data ColorCount = List.Count ( ColorList ), // Get a random number RandomNumber = Number.Random (), // Need an Integer column IntegerColumn = [ProductKey], // Again some random number Index = RandomNumber * IntegerColumn, /* If you divide a random number and get the remainder, the remainder will be between 0 and that number Example = 23 / 16 (Color Count) will return 7, remainder of 215356565423 / 16 will be 15 remainder of 215356565424 / 16 will be 0 */ Mod = Number.Mod ( Index, ColorCount ), // Rounded the number to get the integer part Round = Number.RoundDown ( Mod ), /* using Index Lookup we can get the random color from ColorList ? is just to ensure if there is an error then return null instead You can try yourself -> ColorList{Round + 1} */ Result = ColorList{Round}? in Result, type text )
AntrikshSharma
Community Champion
3 years agoValeriaBreve I have split the code intor variables/step and commented the code so that it is easy to understand:
Table.AddColumn (
Source,
"Color",
each
let
/*
Get the Color Column as a list
You can also use List.Buffer in case the code is slow
ColorList = List.Buffer ( Colors[Color] )
*/
ColorList = Colors[Color],
// Count the colors, returns 16 in my data
ColorCount = List.Count ( ColorList ),
// Get a random number
RandomNumber = Number.Random (),
// Need an Integer column
IntegerColumn = [ProductKey],
// Again some random number
Index = RandomNumber * IntegerColumn,
/*
If you divide a random number and get the remainder,
the remainder will be between 0 and that number
Example = 23 / 16 (Color Count) will return 7,
remainder of 215356565423 / 16 will be 15
remainder of 215356565424 / 16 will be 0
*/
Mod = Number.Mod ( Index, ColorCount ),
// Rounded the number to get the integer part
Round = Number.RoundDown ( Mod ),
/*
using Index Lookup we can get the random color from ColorList
? is just to ensure if there is an error then return null instead
You can try yourself -> ColorList{Round + 1}
*/
Result = ColorList{Round}?
in
Result,
type text
)
ValeriaBreve
Post Partisan
3 years agoBeautiful, thank you so much for taking the time to explain! 🙂 It is clear now!