python - 一个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。但是,我不知道如何平均相邻列。
任何帮助,将不胜感激!
解决方案
您可以使用此代码段来解决您的问题。
# 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 = []
推荐阅读
- c++ - 在 CMake 中使用 protobuf 作为 ExternalProject
- python - 用 Python 发送 Telegram 键盘
- jquery - Highcharts :: Pie :: 添加特定系列的图标
- php - Wordpress 主题崩溃,并且 wp-admin 无法正常工作 - php 问题
- android - RecyclerView 不滚动
- php - 将 php 连接到 microsoft sql 服务器
- python - Python regex - 在 regex101.com 中使用 re.findall() v/s clean 组进行零长度匹配
- android - camera2 api图片是黑暗的android
- ios - Apple 要求使用 Parse-iOS-SDK 对 info.plist 进行“NSLocationAlwaysUsageDescription”描述
- wordpress - WordPress 用户角色