根据其他列中的值,对特定列求平均值

4
我想根据另一列是否满足条件,对某些列值进行平均。具体而言,如果下面数据帧中的第一列小于1700,则我想在我的平均计算中包括该行从第51列中对应的值。如果第二列小于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)

这个回答解决了你的问题吗?按特定行计算特定列的平均值 - Gonçalo Peres
3个回答

3

与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()

新的数据框现在看起来像这样

       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

1
使用Pandas的where是我寻找的方法,可以与布尔数据框一起使用,而不是典型的系列掩码。好答案! - m13op22

1
我删掉了我的另一个答案,因为它走了错误的路。你想要做的是生成一个条件列的掩码,然后使用该掩码将函数应用于其他列。在本例中,1对应于51,2对应于52,依此类推。
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



# create dictionary to map columns to one another
l1=list(range(1,4))
l2=list(range(50,54))
d = {k:v for k,v in zip(l1,l2)}

d
{1: 51, 2: 52, 3: 53}

temp=test_df[l1] > 1700 # Subset initial dataframe, generate mask
for _, row in temp.iterrows(): #iterate through subsetted data
    list_of_columns_for_mean=list() # list of columns for later computation
    for k, v in d.items(): #iterate through each k:v and evaluate conditional for each row
        if row[k]:
            list_of_columns_for_mean.append(v)
            # the rest should be pretty easy to figure out

这并不是一种优雅的解决方案,但它是个解决方案。不幸的是,我已经没有时间再投入到这个问题上了,但是希望这能让你朝更好的方向前进。


1

可能有更好的向量化方法来完成此操作,但您也可以在不使用函数的情况下完成它。

import numpy as np
import pandas as pd
from collections import defaultdict

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]})

# List of columns that you're applying the condition to
condition_cols = list(range(1,4))

# Get row and column indices where this condition is true
condition = np.where(test_df[condition_cols].lt(1700))

# make a dictionary mapping row to true columns
cond_map = defaultdict(list)
for r,c in zip(*condition):
    cond_map[r].append(c)

# Get the means of true columns
means = []
for row in range(len(test_df)):
    if row in cond_map:
        temp = []
        for col in cond_map[row]:
            # Needs 51 because of Python indexing starting at zero + 50
            temp.append(test_df.loc[row, col+51])
        means.append(temp)
    else:
        # If the row has no true columns (i.e row 4)
        means.append(np.nan)

test_df['Means'] = [np.mean(l) for l in means]   

问题在于以矢量化的方式对真实行和列进行索引。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接