gpt4 book ai didi

python - 根据其他列中的值平均某些列

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:09 24 4
gpt4 key购买 nike

我想根据另一列中是否满足条件来计算某些列值的平均值。具体来说,如果下面数据框中的第 1 列 < 1700,我想在我的平均计算中包括第 51 列该行中的相应值。如果第 2 列 < 1700,我还想在我的平均计算中包括第 52 列该行中的值。

因此,对于第 0 行,该行的新计算列将为 64(65 和 63 的平均值)。对于第 1 行,平均值仅为 80(第 51 列值),因为第 2 列和第 3 列均不小于 1700,因此不包括在平均值计算中。

这是一个简化的示例,因为我的实际数据框有大约 10 列条件,其中 10 列对应的值要平均。

作为一个潜在的复杂性,列标题是数字而不是传统的文本标签,并且不引用数据框中该列的顺序,因为我在导入 csv 文件时排除了某些列。换句话说,第 51 列不是数据框中的第 51 列。

当我运行下面的代码时,出现以下错误:

ValueError: ("No axis named 1 for object type ", 'occurred at index 0')

有没有更有效的方法来编码并避免这个错误?感谢您的帮助!

import pandas as pd
import numpy as np

test_df = pd.DataFrame({1:[1600,1600,1600,1700,1800],2:[1500,2000,1400,1500,2000],
3:[2000,2000,2000,2000,2000],51:[65,80,75,80,75],52:[63,82,85,85,75],53:[83,80,75,76,78]})

test_df

1 2 3 51 52 53
0 1600 1500 2000 65 63 83
1 1600 2000 2000 80 82 80
2 1600 1400 2000 75 85 75
3 1700 1500 2000 80 85 76
4 1800 2000 2000 75 75 78


def calc_mean_based_on_conditions(row):

list_of_columns_to_average = []
for i in range(1,4):
if row[i] < 1700:
list_of_columns_to_average.append(i+50)

if not list_of_columns_to_average:
return np.nan
else:
return row[(list_of_columns_to_average)].mean(axis=1)

test_df['MeanValue'] = test_df.apply(calc_mean_based_on_conditions, axis=1)

最佳答案

非常相关的东西(支持 int 作为列名)- https://github.com/theislab/anndata/issues/31

由于这个错误/问题,我将列名转换为字符串类型:

test_df = pd.DataFrame({'1':[1600,1600,1600,1700,1800],'2':[1500,2000,1400,1500,2000],
'3':[2000,2000,2000,2000,2000],'51':[65,80,75,80,75],'52':[63,82,85,85,75],'53':
[83,80,75,76,78]})

创建了一个新的数据框 - new_df 以满足要求

new_df = test_df[['1', '2', '3']].where(test_df[['1','2','3']]<1700).notnull()

new_df 现在看起来像这样

       1      2      3
0 True True False
1 True False False
2 True True False
3 False True False
4 False False False

然后只需重命名该列并使用“where”进行检查

new_df = new_df.rename(columns={"1": "51", "2":"52", "3":"53"})
test_df['mean_value'] = test_df[['51', '52', '53']].where(new_df).mean(axis=1)

这应该会为您提供所需的输出 -

    1     2     3  51  52  53  mean_value
0 1600 1500 2000 65 63 83 64.0
1 1600 2000 2000 80 82 80 80.0
2 1600 1400 2000 75 85 75 80.0
3 1700 1500 2000 80 85 76 85.0
4 1800 2000 2000 75 75 78 NaN

关于python - 根据其他列中的值平均某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58203963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com