簡體   English   中英

pandas 當另一列與 python 中的值匹配時,僅獲取一列的平均值(浮點)

[英]pandas Getting just the mean (float) value of one column when another column matches value in 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

這被導入到 pandas 數據框中,索引為制造商。 在這個例子中,我想要圓形彈珠的平均值。 我現在擁有的返回一個系列:

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

我不想返回一個系列,我只想要彈珠的浮點數。

您正在傳遞一個列名列表,該列表返回一個系列,因為該列表中的每個數字列都有一個平均值。

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

傳入標量列標簽會返回一個浮點數。

你可以擁有所有形狀的平均值

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

shape    marbles
round    262.25
square   257.00

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM