[英]add column to groups on dataframe pandas
我有一个数据框:
id | x | y
1 | 0.3 | 0.4
1 | 0.2 | 0.5
2 | 0.1 | 0.6
2 | 0.9 | 0.1
3 | 0.8 | 0.2
3 | 0.7 | 0.3
如何相对于 id 列向数据框添加新列?
例如:
id | x | y | color
1 | 0.3 | 0.4 | 'green'
1 | 0.2 | 0.5 | 'green'
2 | 0.1 | 0.6 | 'black'
2 | 0.9 | 0.1 | 'black'
3 | 0.8 | 0.2 | 'red'
3 | 0.7 | 0.3 | 'red'
因此,您的函数不返回颜色名称,而是返回 RGB 值,如果这是您想要的颜色列,则首先从唯一的 id 值构建字典,并按照注释中提到的 @anky_91 方式应用字典。
d={x:random_color() for x in df.id.unique()}
df['color']=df['id'].map(d)
可能为时已晚,但如果您想要替代方案,这是另一种具有简单功能的方法:
colors = ['Green', 'Black', 'Red']
def color(data):
if data['id'] == 1:
col = colors[0]
if data['id'] == 2:
col = colors[1]
if data['id'] == 3:
col = colors[2]
return col
df['Colors'] = df.apply(color, axis = 1)
print(df)
# id x y Colors
# 0 1 0.3 0.4 Green
# 1 1 0.2 0.5 Green
# 2 2 0.1 0.6 Black
# 3 2 0.9 0.1 Black
# 4 3 0.8 0.2 Red
# 5 3 0.7 0.3 Red
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.