[英]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.