在Pandas Groupby和Agg Funcion中使用if/else语句
让我们考虑下面的这个数据帧
df = pd.DataFrame([('Bike', 'Kawasaki', 130 , 186),
('Bike', 'Ducati Panigale' , 135 , 202),
('Car', 'Bugatti Chiron' , 461 , 304),
('Car', 'Jaguar XJ220', 472 , 210),
('Bike', 'Lightning LS-218' , 137 , 218),
('Car', 'Hennessey Venom GT' , 523 , 270),
('Bike', 'BMW S1000RR' , 174 , 188)],
columns =('Type', 'Name', 'Length' ,'top_speed(mph)'))
我想做的是计算长度和最高速度的最小值、最大值、平均值、中值和标准差,但每个数值变量都有一个 If/Else 条件。
这就是我现在所做的:
df.groupby(["Type"]).agg(
{
"Length": ["max", "min", "mean", "median", "std"],
"top_speed(mph)": ["max", "min", "mean", "median", "std"],
},
axis=1,
)
我想计算长度最小值、最大值等 if Type == Bike else None
并计算 top_speed 最小值、最大值等 if类型 == 其他汽车无
。我知道我们可以使用 lambda 函数,但如果我们需要大量计算一件事,这里我必须为每个值计算 5 个值
Let's consider this dataFrame below
df = pd.DataFrame([('Bike', 'Kawasaki', 130 , 186),
('Bike', 'Ducati Panigale' , 135 , 202),
('Car', 'Bugatti Chiron' , 461 , 304),
('Car', 'Jaguar XJ220', 472 , 210),
('Bike', 'Lightning LS-218' , 137 , 218),
('Car', 'Hennessey Venom GT' , 523 , 270),
('Bike', 'BMW S1000RR' , 174 , 188)],
columns =('Type', 'Name', 'Length' ,'top_speed(mph)'))
What i'ld like to do is compute min, max, mean, median and std for Length and top speed but with an If/Else condition for each numerical variable.
This is what i do now:
df.groupby(["Type"]).agg(
{
"Length": ["max", "min", "mean", "median", "std"],
"top_speed(mph)": ["max", "min", "mean", "median", "std"],
},
axis=1,
)
I'ld like to compute Length min, max etc if Type == Bike else None
and compute top_speed min, max etc if Type == Car else None
. I know we can use a lambda function but in the case we need ton compute one thing, here i have to compute 5 values for each
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
打印:
Try:
Prints: