我想根据另一列中是否满足条件来平均某些列值。具体来说,如果下面数据框中的第 1 列 因此,对于第 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 pdimport numpy as nptest_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 530 1600 1500 2000 65 63 831 1600 2000 2000 80 82 802 1600 1400 2000 75 85 753 1700 1500 2000 80 85 764 1800 2000 2000 75 75 78def 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 30 True True False1 True False False2 True True False3 False True False4 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_value0 1600 1500 2000 65 63 83 64.01 1600 2000 2000 80 82 80 80.02 1600 1400 2000 75 85 75 80.03 1700 1500 2000 80 85 76 85.04 1800 2000 2000 75 75 78 NaN关于python - 根据其他列中的值平均某些列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58203963/
10-12 18:14