代码之家  ›  专栏  ›  技术社区  ›  The Great

如何使用pandas标准提取组列表元素

  •  2
  • The Great  · 技术社区  · 3 年前

    我有一个熊猫数据框,如下所示

    ID,color
    1, Yellow
    1, Red
    1, Green
    2, Red
    2, np.nan
    3, Green
    3, Red
    3, Green
    4, Yellow
    4, Red
    5, Green
    5, np.nan
    6, Red
    7, Red
    
    fd = pd.read_clipboard(sep=',')
    

    正如您在输入数据框中看到的,一些ID有多种颜色与之关联。

    因此,每当有多种颜色与它们关联时,我只想根据以下标准选择一种颜色

    ['Green','Red','Yellow'] = Choose 'Green'
    ['Red', 'Yellow'] = Choose 'Yellow'
    ['Green', 'Yellow'] = Choose 'Green'
    

    大体上 绿色优先。第二个偏好是黄色,最后一个偏好是红色。

    所以,如果一个ID有绿色,选择绿色(不关心其他颜色)。

    如果ID有黄色和红色,请选择黄色

    如果其所有行的ID只有 NA ,保持原样

    我尝试了下面的方法,但这只能得到颜色列表

    fd.groupby('ID',as_index=False)['color'].aggregate(lambda x: list(x))
    fd[final_color] = [if i[0] =='Green' for i in fd[col]]
    

    我希望我的输出如下所示

    enter image description here

    使现代化

    enter image description here

    3 回复  |  直到 3 年前
        1
  •  2
  •   Shubham Sharma mkln    3 年前

    在首选项字典的帮助下,按颜色对dataframe的值进行排序,然后将重复项放到 ID

    d = {'Green': 1, 'Yellow': 2, 'Red': 3}
    df.sort_values('color', key=lambda c: c.map(d)).drop_duplicates('ID')
    

    通过首先转换 color 列到 有序范畴型 ,然后groupby和aggregate选择最小值

    df['color'] = pd.Categorical(df['color'], ['Green', 'Yellow', 'Red'], True)
    df.groupby('ID', as_index=False)['color'].agg('min')
    

       ID   color
    0   1   Green
    1   2     Red
    2   3   Green
    3   4  Yellow
    4   5   Green
    5   6     Red
    6   7     Red
    
        2
  •  1
  •   SultanOrazbayev    3 年前

    解决此问题的一种方法是实现自定义排序:

    sort_preference = {
        'Green': 0,
        'Yellow': 1,
    }
    
    (
        fd
        .sort_values(by=['color'], key=lambda x: x.map(sort_preference))
        .groupby('ID')
        .head(1)
    )
    
        3
  •  1
  •   Corralien    3 年前

    无需排序,您可以使用 idxmin 如果使用数值映射颜色:

    d = {'Green': 1, 'Yellow': 2, 'Red': 3}
    out = df.loc[df.assign(num=df['color'].map(d)).groupby('ID')['num'].idxmin()]
    print(out)
    
    # Output
        ID   color
    2    1   Green
    3    2     Red
    5    3   Green
    8    4  Yellow
    10   5   Green
    12   6     Red
    13   7     Red