【问题标题】:How to find the average of data samples at random intervals in python?如何在python中以随机间隔找到数据样本的平均值?
【发布时间】:2021-03-02 23:36:14
【问题描述】:

绘制时,我将温度数据存储在 csv 文件中,如下图所示。当温度高于 12 时,我如何找到每个间隔内的平均值。结果应该是 T1,T2,T3,这应该是其值高于 12 的间隔内的平均温度。 您能否建议如何在 python 中实现这一目标?

突出显示我需要计算平均值的大致区域:

请查看以下示例数据:

R3,R4
1,11
2,11
3,11
4,11
5,11
6,15.05938512
7,15.12975992
8,15.05850141
18,15.1677708
19,15.00921862
20,15.00686921
21,15.01168888
22,11
23,11
24,11
25,11
26,11
27,15.05938512
28,15.12975992
29,15.05850141
30,15.00328706
31,15.12622611
32,15.01479819
33,15.17778891
34,15.01411488
35,9
36,9
37,9
38,9
39,16.16042435
40,16.00091253
41,16.00419677
42,16.15381827
43,16.0471766
44,16.03725301
45,16.13925003
46,16.00072279
47,11
48,1

【问题讨论】:

  • 请提供文本格式的数据。

标签: python python-3.x pandas python-2.7 numpy


【解决方案1】:

我找不到一个很好的模式 - 不过,这里有一段笨拙的代码可以满足你的要求。

一般来说,使用 .shift() 来查找转换点,并使用 groupby 和 transform 来获得你的手段。

#if you had a csv with Dates and Temps, do this
#tempsDF = pd.read_csv("temps.csv", columns=["Date","Temp"])  
#tempsDF.set_index("Date", inplace=True)
#Using fake data since I don't have your csv
tempsDF = pd.DataFrame({'Temp': [0,13,14,13,8,7,5,0,14,16,16,0,0,0]})
#This is a bit clunky - I bet there's a more elegant way to do it
tempsDF["CumulativeFlag"] = 0
tempsDF.loc[tempsDF["Temp"]>12, "CumulativeFlag"]=1
tempsDF.loc[tempsDF["CumulativeFlag"] > tempsDF["CumulativeFlag"].shift(), "HighTempGroup"] = list(range(1,len(tempsDF.loc[tempsDF["CumulativeFlag"] > tempsDF["CumulativeFlag"].shift()])+1))
tempsDF["HighTempGroup"].fillna(method='ffill', inplace=True)
tempsDF.loc[tempsDF["Temp"]<=12, "HighTempGroup"]= None
tempsDF["HighTempMean"] = tempsDF.groupby("HighTempGroup").transform(np.mean)["Temp"]

【讨论】:

    【解决方案2】:

    在 pandas 中,一个想法是根据条件 T &gt; 12 对数据进行分组,并使用均值作为 agg func。例如:

    import pandas as pd
    # a dummy df:
    df = pd.DataFrame({'T': [11, 13, 13, 10, 14]})
    # set the condition
    m = df['T'] > 12
    # define groups
    grouper = (~m).cumsum().where(m)
    # ...looks like
    # 0    NaN
    # 1    1.0
    # 2    1.0
    # 3    NaN
    # 4    2.0
    # Name: T, dtype: float64
    
    # now we can easily calculate the mean for each group:
    grp_mean = df.groupby(grouper)['T'].mean()
    # T
    # 1.0    13
    # 2.0    14
    # Name: T, dtype: int64
    

    注意:如果您有嘈杂的数据(T 上下跳动),首先应用过滤器(savgol、中值等 - 任何合适的)可能会很聪明,这样您就不会得到由噪音。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-09
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多