Reputation: 315
I have a column that contains multiple values in each row. I am trying to write a function to select just one value of each row based on a priority list, so that is reduced just to one value. I am using python.
my column looks like this:
Green&Yellow
Yellow
Blue&Orange
Orange&Green
Purple&Green
Purple
Yellow&Purple
Green
My priority list is:
Priority_list = [Green, Orange, Blue, Purple, Yellow ]
The desired output would be:
Green
Yellow
Orange
Green
Green
Purple
Purple
Green
The code should be something like this:
def select_color(value):
color = value.split('&')
if len(color) > 1:
my_color = first color found in list
else:
my_color = color
return my_color
I can't find the way to select the first value appearing in the priority list.
Thanks a lot,
Rachael
Upvotes: 1
Views: 1142
Reputation: 1155
More simple you can try:
import re
c = ["Green&Yellow","Yellow","Blue&Orange","Orange&Green","Purple&Green","Purple","Yellow&Purple","Green"]
p = ["Green", "Orange", "Blue", "Purple", "Yellow" ]
[[re.findall('(?i)(' + v + ').*?', x) for v in p if re.findall('(?i)(' + v + ').*?', x)][0][0] for x in c]
the results:
['Green', 'Yellow', 'Orange', 'Green', 'Green', 'Purple', 'Purple', 'Green']
Upvotes: 1
Reputation: 575
If all your color in priority_list then below code will help you
priority_list = [Green, Orange, Blue, Purple, Yellow ]
def select_color(value):
color = value.split('&')
if len(color) == 1:
return color[0]
else:
for pcolor in priority_list:
if pcolor in color :
return pcolor;
Upvotes: 0
Reputation: 943
# list = Global list of colors that you want
# color = string col1&col2&col3...
def select_color(list, color):
color_list = color.split('&')
for col in color_list:
if col in list:
return col
return
if you get None as return value that means that the color is not found
Upvotes: 0