【问题标题】:How to group Pandas rows and present the output as dictionary in Python?如何在 Python 中对 Pandas 行进行分组并将输出呈现为字典?
【发布时间】: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) 

问题是我添加了“名字”列中包含的所有名称以及每种颜色的眼睛。

【问题讨论】:

标签: python loops dataframe dictionary conditional-statements


【解决方案1】:

此代码遍历df 的所有行并将first name 添加到eye color 的dict 条目中。对于第一次出现的颜色 (color not in output),必须在 dict 中创建条目,并将其初始化为空列表 (output[color] = [])。

output = {}

for i in range(len(df)):

    color = df['eye color'][i]
    first_name = df['first name'][i]

    if color not in output:
        output[color] = []
    output[color].append(first_name)
    
print(output)

【讨论】:

  • 我更了解我的错误。谢谢。
猜你喜欢
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 2013-08-13
  • 2013-03-28
  • 1970-01-01
  • 2019-11-16
相关资源
最近更新 更多