聚合具有相同id号的行并根据聚合输入列值

时间:2021-01-12 00:16:06

标签: python pandas dataframe for-loop if-statement

df = pandas.DataFrame( { 
    "ID" : ["1123", "2325", "9788", "1123", "9788" , "5421"] , 
    "Type" : ["Red", "Black", "Black", "Black", "Red", "Black"] } )

df 应如下所示 - 请注意,ID 号 1123 和 9788 同时具有黑色和红色“类型”

     ID     Type
0   1123     Red
1   2323    Black
2   9788    Black
3   1123    Black
4   9788     Red
5   5421    Black

我想编写一些聚合行的代码。如果 ID 号同时具有黑色和红色“类型”,我希望它显示为红色,否则为黑色,如下所示。

     ID     Type
0   1123    Red
1   2323    Black
2   9788    Red
3   5421    Black

2 个答案:

答案 0 :(得分:1)

只需 pip install opencv-contrib-python 并取 groupby 值(因为“红色”>“黑色”):

max

输出:

df.groupby('ID', as_index=False)['Type'].max()

更新:如果您有更多类型,您可以转换为有序分类,指定所需的顺序,然后以完全相同的方式使用 ID Type 0 1123 Red 1 2325 Black 2 5421 Black 3 9788 Red groupby

max

这里我们将有“黑”<“绿”<“蓝”<“红”

答案 1 :(得分:0)

类型按顺序排序,drop_duplicates按“ID”,保留你想要的类型。

df['order_tag'] = df['Type'].map({'Red':1,'Black':2})
df.sort_values('order_tag').drop_duplicates('ID', keep='first').sort_index()

输出:

     ID   Type  order_tag
0  1123    Red          1
1  2325  Black          2
4  9788    Red          1
5  5421  Black          2