首页 > 解决方案 > 一个pandas列的累积总和,直到达到最大值,平均相邻行

问题描述

我是一名生物学学生,对 python 还很陌生,希望有人能够帮助我解决我尚未解决的问题

使用一些后续代码,我创建了一个 pandas 数据框,如下例所示:

Distance.     No. of values        Mean rSquared
    1                   500                  0.6
    2                    80                  0.3
    3                    40                  0.4
    4                    30                  0.2
    5                    50                  0.2
    6                    30                  0.1

我可以提供我以前的代码来创建这个数据框,但我认为它不是特别相关。

我需要对列的数量求和,直到达到 >= 100;然后结合相邻列的行的数据,取距离和均值r2值的加权平均,如下例所示

Mean Distance.             No. Of values             Mean rSquared
1                          500                       0.6
(80*2+40*3)/120            (80+40) = 120             (80*0.3+40*0.4)/120
(30*4+50*5+30*6)/110       (30+50+30) = 110          (30*0.2+50*0.2+30*0.1)/110

etc...

我知道 pandas 有它的.cumsum功能,我可以for用一个语句来实现一个循环,该if语句检查上限并在总和大于或等于上限时将总和重置回 0。但是,我不知道如何平均相邻列。

任何帮助,将不胜感激!

标签: pythonpandascumulative-sumweighted-average

解决方案


您可以使用此代码段来解决您的问题。

# First, compute some weighted values
df.loc[:, "weighted_distance"] = df["Distance"] * df["No. of values"]
df.loc[:, "weighted_mean_rSquared"] = df["Mean rSquared"] * df["No. of values"]


min_threshold = 100
indexes = []
temp_sum = 0

# placeholder for final result
final_df = pd.DataFrame()
columns = ["Distance", "No. of values", "Mean rSquared"]

# reseting index to make the 'df' usable in following output
df = df.reset_index(drop=True)

# main loop to check and compute the desired output
for index, _ in df.iterrows():
    temp_sum += df.iloc[index]["No. of values"]
    indexes.append(index)

    # if the sum exceeds 'min_threshold' then do some computation
    if temp_sum >= min_threshold:
        temp_distance = df.iloc[indexes]["weighted_distance"].sum() / temp_sum
        temp_mean_rSquared = df.iloc[indexes]["weighted_mean_rSquared"].sum() / temp_sum
    
        # create temporary dataframe and concatenate with the 'final_df'
        temp_df = pd.DataFrame([[temp_distance, temp_sum, temp_mean_rSquared]], columns=columns)
        final_df = pd.concat([final_df, temp_df])
    
        # reset the variables
        temp_sum = 0
        indexes = []

推荐阅读