[英]Change pandas dataframe column values based on other columns in dataframe
[英]Change the value of a pandas dataframe column based on a condition ,also depending on other columns of the dataframe
Category DishName Id
0 a Pistachio 621f4884e48bc60012364b13
1 a Pistachio 621f4884e48bc60012364b13
2 a Pistachio 621f4884e48bc60012364b13
3 a achar 621f4884e48bc60012364b13
4 b achar 621f4884e48bc60012364b13
5 b achar 621f4884e48bc60012364b13
6 a chicken 621f4884e48bc60012364b13
7 b chicken 621f4884e48bc60012364b13
8 c chicken 621f4884e48bc60012364b13
我的數據框有 3 列類別、菜名和 ID。 考慮到 id 和菜名,我必須分配類別。
如果所有類別值都是“a”,則分配“a”
如果類別值為“a”、“b”,則分配“b”
如果類別值為“a”、“b”、“c”,則分配“c”
預期輸出為
Category DishName Id
0 a Pistachio 621f4884e48bc60012364b13
1 a Pistachio 621f4884e48bc60012364b13
2 a Pistachio 621f4884e48bc60012364b13
3 b achar 621f4884e48bc60012364b13
4 b achar 621f4884e48bc60012364b13
5 b achar 621f4884e48bc60012364b13
6 c chicken 621f4884e48bc60012364b13
7 c chicken 621f4884e48bc60012364b13
8 c chicken 621f4884e48bc60012364b13
您可以轉換為有序分類並獲得每組的最大值:
df['Category'] = (pd
.Series(pd.Categorical(df['Category'],
categories=['a', 'b', 'c'], ordered=True),
index=df.index)
.groupby(df['DishName'])
.transform('max')
)
注意。 您不需要簡單的分類a, b, c
,因為這三個是按字典順序排序的,但我想現實生活中的情況不一定如此。 例如low < medium < high
在邏輯上但不是按字典排序。
輸出:
Category DishName Id
0 a Pistachio 621f4884e48bc60012364b13
1 a Pistachio 621f4884e48bc60012364b13
2 a Pistachio 621f4884e48bc60012364b13
3 b achar 621f4884e48bc60012364b13
4 b achar 621f4884e48bc60012364b13
5 b achar 621f4884e48bc60012364b13
6 c chicken 621f4884e48bc60012364b13
7 c chicken 621f4884e48bc60012364b13
8 c chicken 621f4884e48bc60012364b13
df['Category'] = df.groupby('DishName')['Category'].transform('max')
輸出:
Category DishName Id
0 a Pistachio 621f4884e48bc60012364b13
1 a Pistachio 621f4884e48bc60012364b13
2 a Pistachio 621f4884e48bc60012364b13
3 b achar 621f4884e48bc60012364b13
4 b achar 621f4884e48bc60012364b13
5 b achar 621f4884e48bc60012364b13
6 c chicken 621f4884e48bc60012364b13
7 c chicken 621f4884e48bc60012364b13
8 c chicken 621f4884e48bc60012364b13
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.