从默认部分中的 numpy 条件逻辑返回列值
returning a column value from a numpy conditional logic in the default section
我有一个数据框如下:
COLOR
1 grey
2 white
3 black
4 orange
5 pink
6 red
7 blue
8 green
我想在数据框中添加另一列,它设置了一个新的颜色列,可以根据特定条件分配值,并在不满足条件时保持已分配的颜色。这是我想要的最终结果:
COLOR FINAL_COLOR
1 grey black
2 white black
3 black black
4 orange red
5 pink red
6 red red
7 blue blue
8 green green
这是我尝试过的:
condition = [(df['color'] == 'grey'),
(df['color'] == 'white'),
(df['color'] == 'orange'),
(df['color'] == 'pink')]
result = ['black','red']
df['final_color'] = np.select(condition,result,default = df['color'])
这就是你所要求的。
def get_final_color(val):
color = val.lower()
if color in ['grey', 'white', 'black']:
return 'black'
elif color in ['orange', 'pink', 'red']:
return 'red'
else:
return color
df = pd.DataFrame(
data = {'COLOR': ['grey', 'white', 'black', 'orange', 'pink', 'red', 'blue', 'green']})
df['FINAL_COLOR'] = df['COLOR'].apply(get_final_color)
根据您的尝试,这可能是一个很好的解决方案,或者请提供更多详细信息,以便我修改此答案以提供更多帮助!
我有一个数据框如下:
COLOR
1 grey
2 white
3 black
4 orange
5 pink
6 red
7 blue
8 green
我想在数据框中添加另一列,它设置了一个新的颜色列,可以根据特定条件分配值,并在不满足条件时保持已分配的颜色。这是我想要的最终结果:
COLOR FINAL_COLOR
1 grey black
2 white black
3 black black
4 orange red
5 pink red
6 red red
7 blue blue
8 green green
这是我尝试过的:
condition = [(df['color'] == 'grey'),
(df['color'] == 'white'),
(df['color'] == 'orange'),
(df['color'] == 'pink')]
result = ['black','red']
df['final_color'] = np.select(condition,result,default = df['color'])
这就是你所要求的。
def get_final_color(val):
color = val.lower()
if color in ['grey', 'white', 'black']:
return 'black'
elif color in ['orange', 'pink', 'red']:
return 'red'
else:
return color
df = pd.DataFrame(
data = {'COLOR': ['grey', 'white', 'black', 'orange', 'pink', 'red', 'blue', 'green']})
df['FINAL_COLOR'] = df['COLOR'].apply(get_final_color)
根据您的尝试,这可能是一个很好的解决方案,或者请提供更多详细信息,以便我修改此答案以提供更多帮助!