【发布时间】:2020-11-22 16:42:26
【问题描述】:
我想为每个类别/眼睛颜色获取所有关联的名字。
这是我的数据框 (df):
eye color first name
0 blue Jules
1 blue Lucie
2 green Thomas
3 green Vincent
4 green David
5 brown Maxime
这是我想要的输出:
{'blue': ['Jules', 'Lucie'], 'green': ['Thomas', 'Vincent', 'David'], 'brown': ['Maxime']
这是我的代码:
list_name=list()
for i in range(len(df)-1):
current_color=df['eye color'][i]
next_color=df['eye color'][i+1]
name=df['first name'][i]
if current_color!=next_color :
compte_nb_systeme=compte_nb_systeme+1
print('we change eye color')
else :
print('we don't change the color of the eye')
list_name.append(name)
dico= {current_color :list_name}
print(dico)
问题是我添加了“名字”列中包含的所有名称以及每种颜色的眼睛。
【问题讨论】:
-
df.groupby('eye color')['first name'].apply(list).to_dict()? -
它工作正常。感谢您的帮助。
-
是的,这正是我想要的。
标签: python loops dataframe dictionary conditional-statements