当另一列与python中的值匹配时,只获取一列的平均值(float)

2024-09-30 02:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一张简单的桌子

manufacturer    marbles     shape     blah
A               169         square    yada
B               140         round     yada
C               420         round     yada
C               380         square    random
D               400         round     dontmatter
D               222         square    lkj
D                89         round     asdf

这被导入到一个索引为manufacturer的pandas数据帧中。在这个例子中,我想要形状为圆形的大理石的平均值。我现在返回的是一个系列:

return df.loc[df['shape'] == 'round', ["marbles"]].mean()

我不想一个系列的回报,我只想浮动平均数弹珠


Tags: 数据pandasdfrandomblahshapesquare桌子
2条回答

您正在传入一个列名列表,该列表返回一个序列,因为该列表中的每个数字列都有一个平均值

df.loc[df['shape'] == 'round', "marbles"].mean()

传入标量列标签将返回浮点值

你可以拥有所有形状的平均值

df.groupby('shape', as_index=False).agg({'marbles': 'mean'})

shape    marbles
round    262.25
square   257.00

相关问题 更多 >

    热门问题