社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python:groupby,根据其他列的最大值创建新列[duplicate]

julien1337 • 5 年前 • 1969 次点击  

我有一个包含位置ID、商店名称和商店收入的数据框。我想确定每个地区收入最高的商店

我为此写了一个代码,但不确定是否有更好的方法来处理这个案子

import pandas as pd    
dframe=pd.DataFrame({"Loc_Id":[1,2,2,1,2,1,3,3],"Store":["A","B","C","B","D","B","A","C"],
                 "Revenue":[50,70,45,35,80,70,90,65]})

#group by location id, then save max per location in new column
dframe["max_value"]=dframe.groupby("Loc_Id")["Revenue"].transform(max)

#create new column by checking if the revenue equal to max revenue
dframe["is_loc_max"]=dframe.apply(lambda x: 1 if x["Revenue"]==x["max_value"] else 0,axis=1)

#drop the intermediate column 
dframe.drop(columns=["max_value"],inplace=True)

这是所需的输出: ![enter image description here

有没有更好的方法得到这个输出

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40547
 
1969 次点击  
文章 [ 1 ]  |  最新文章 5 年前