I have a dataframe with year-month as index. I want to assign a color to the dataframe based on the year the sample was collected.
import matplotlib.colors as mcolors
colors_list = list(mcolors.XKCD_COLORS.keys())
colors_list =
['xkcd:cloudy blue',
'xkcd:dark pastel green',
'xkcd:dust',
'xkcd:electric lime',
'xkcd:fresh green',
'xkcd:light eggplant'
........
]
df =
sensor_value Year Month
0 5171.318942 2002 4
1 5085.094086 2002 5
3 5685.681944 2004 6
4 6097.877688 2006 7
5 6063.909946 2003 8
.....
years_list = df['Year'].unique().tolist()
req_colors_list = colors_list[:len(years_list)]
df['year_color'] = df['Year'].apply(lambda x: clr if x==year else np.nan for year,clr in zip(years_list,req_colors_list))
Present output:
<lambda> <lambda> <lambda> <lambda> <lambda> <lambda> <lambda> <lambda> <lambda> <lambda>
Year
2002 tab:blue NaN NaN NaN NaN NaN NaN NaN NaN NaN
2002 tab:blue NaN NaN NaN NaN NaN NaN NaN NaN NaN
2006 tab:blue NaN NaN NaN NaN NaN NaN NaN NaN NaN
2006 tab:blue NaN NaN NaN NaN NaN NaN NaN NaN NaN
2003 tab:blue NaN NaN NaN NaN NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ... ... ... ...
Expected output:
2002 'xkcd:cloudy blue'
2002 'xkcd:cloudy blue'
2006 'xkcd:fresh green'
2006 'xkcd:fresh green'
2003