Reputation: 1546
Suppose I have a DataFrame with the following columns:
import pandas as pd
df = pd.DataFrame({
'strings': ['Wut?', 'Random', 'Citruna', 'FlatEarth', 'ElonMusk'],
'postcode': [97700, 04130, 33210, 00520, 97700]})
Problem: I want to create a new column that would take the values in df["postcode"] and use it as a seed to generate a random HEX colour. How can this be done?
Upvotes: 1
Views: 191
Reputation: 8663
Below is an example of how you could apply this solution to your problem.
import numpy as np
import pandas as pd
def color(seed):
np.random.seed(seed)
return '#%02X%02X%02X' % tuple(np.random.randint(0, 255, 3))
df = pd.DataFrame({
'strings': ['Wut?', 'Random', 'Citruna', 'FlatEarth', 'ElonMusk'],
'postcode': ['97700', '04130', '33210', '00520', '97700']
})
df['color'] = df['postcode'].astype(int).apply(lambda x: color(x))
print(df)
# strings postcode color
# 0 Wut? 97700 #E60997
# 1 Random 04130 #FEDC98
# 2 Citruna 33210 #218F90
# 3 FlatEarth 00520 #AC6B9B
# 4 ElonMusk 97700 #E60997
Upvotes: 2