绘制熊猫数据框子集的平均值

时间:2019-03-28 21:36:45

标签: python pandas plot statistics

假设像

这样的大量数据
   Height (m)  My data
0          18      5.0
1          25      6.0
2          10      1.0
3          13      1.5
4          32      8.0
5          26      6.7
6          23      5.0
7           5      2.0
8           7      2.0

我想绘制“我的数据”的平均值(如果可能的话,还有标准偏差)作为高度的函数,其范围为[0,5),[5,10),[10, 15)等等。

有什么主意吗?我尝试了不同的方法,但没有一个起作用

2 个答案:

答案 0 :(得分:2)

如果我对您的理解正确:

# Precompute bins for pd.cut
bins = list(range(0, df['Height (m)'].max() + 5, 5))

# Cut Height into intervals which exclude the right endpoint, 
# with bin edges at multiples of 5
df['HeightBin'] = pd.cut(df['Height (m)'], bins=bins, right=False)

# Within each bin, get mean, stdev (normalized by N-1 by default),
# and also show sample size to explain why some std values are NaN
df.groupby('HeightBin')['My data'].agg(['mean', 'std', 'count'])
            mean       std  count
HeightBin
[0, 5)       NaN       NaN      0
[5, 10)     2.00  0.000000      2
[10, 15)    1.25  0.353553      2
[15, 20)    5.00       NaN      1
[20, 25)    5.00       NaN      1
[25, 30)    6.35  0.494975      2
[30, 35)    8.00       NaN      1

答案 1 :(得分:1)

如果我理解正确,这就是您想要做的:

import pandas as pd
import numpy as np

bins = np.arange(0, 30, 5) # adjust as desired

df_stats = pd.DataFrame(columns=['mean', 'st_dev']) # DataFrame for the results
df_stats['mean'] = df.groupby(pd.cut(df['Height (m)'], bins, right=False)).mean()['My data']
df_stats['st_dev'] = df.groupby(pd.cut(df['Height (m)'], bins, right=False)).std()['My data']
相关问题