python - 如何根据另一列的每组最大值将一列的标签分配给新的标签? Pandas 变形

标签 python python-3.x pandas machine-learning

我在 Pandas 中有以下示例数据框。如何获取每个 'Id' 的 'label_weight' 值的最大值并将相应的 'label' 列分配给该 'Id' 在新列 'assgined_label'

df = pd.DataFrame(columns=['Id', 'label_weight', 'label'])

df['Id'] = ['A','A','A','A','B','B','B','B','C','C','C','C']
df['label'] = ['H','H', 'H','M', 'H', 'M', 'M', 'L','H', 'H', 'L', 'L']
df['label_weight'] = ['30','30', '30','28', '29','31', '31', '30', '26', '26','28','28']

所需的输出应如下所示:

df['assgined_label'] = ['H','H', 'H','H', 'M','M', 'M','M', 'L','L', 'L','L']

enter image description here 我尝试了类似的方法,但无法产生正确的结果。

df['assgined_label'] = df.groupby('Id')['label_weight']\
                         .transform(lambda x: x.max() x['label'])

感谢任何帮助或提示。

最佳答案

通过 DataFrame.set_index 创建索引通过 DataFrameGroupBy.idxmax 获取索引值与 GroupBy.transform , 因为分配给numpy数组的索引值与原来不同:

#convert column to numeric
df['label_weight'] = df['label_weight'].astype(int)
#pandas 0.24+
df['assigned_label'] = (df.set_index('label')
                          .groupby('Id')['label_weight']
                          .transform('idxmax')
                          .to_numpy())

#pandas below 0.24
df['assigned_label'] = (df.set_index('label')
                          .groupby('Id')['label_weight']
                          .transform('idxmax')
                          .values)

print (df)
   Id  label_weight label assgined_label
0   A            30     H              H
1   A            30     H              H
2   A            30     H              H
3   A            28     M              H
4   B            29     H              M
5   B            31     M              M
6   B            31     M              M
7   B            30     L              M
8   C            26     H              L
9   C            26     H              L
10  C            28     L              L
11  C            28     L              L

关于python - 如何根据另一列的每组最大值将一列的标签分配给新的标签? Pandas 变形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57321417/

相关文章:

python - OpenCV Python HoughCircles 错误

python - Flask:将 Python dict 转换为客户端 api 的 json 对象

python - 根据列中的值删除行中的值,然后在 Pandas 中将单元格拆分为多行

python - pandas groupby 计算一列中零的数量

python - scipy.integrate.odeint 返回错误结果

程序启动后 Python GUI 不更新信息

python - getsizeof() 函数在 Python 2 和 Python 3 中返回不同的输出

python - 参数 'on_delete' 没有值

python - 根据条件将 Pandas DataFrame 列从 String 转换为 Int

php - Python 脚本化 mp3 数据库,带有 php 前端