提问者:小点点

大数据帧中的Pandas加权平均法


我在Pandas中有一个很大的数据集(大约800万行x25列),我正在努力找到一种方法来计算这个数据帧的加权平均数,这反过来又创建了另一个数据帧。

下面是我的数据集的样子(非常简化的版本):

                   prec     temp
location_id hours             
135         1      12.0      4.0
            2      14.0      4.1
            3      14.3      3.5
            4      15.0      4.5
            5      15.0      4.2
            6      15.0      4.7
            7      15.5      5.1
136         1      12.0      4.0
            2      14.0      4.1
            3      14.3      3.5
            4      15.0      4.5
            5      15.0      4.2
            6      15.0      4.7
            7      15.5      5.1

>

  • 我在[location_id,hours]上有一个多索引。 我有大约60k个位置和140小时为每个位置(组成800万行)。

    其余的数据是数值(浮点)或分类的。 我只包括2栏在这里,通常有大约20栏。

    我愿意做的是创建一个新的数据帧,基本上是这个数据帧的加权平均。 需求表明,这些location_id中的12个应该用指定的权重求平均值,以形成combined_location_id值。

    例如,location_idS1,3,5,7,9,11,13,15,17,19,21,23及其适当的权重(来自另一个数据帧的独立数据)应该从combined_location_idcl_1的数据中加权平均。

    要处理的数据太多了,我无法找到一个完全像熊猫一样的方法来解决这个问题。 因此,我使用了for loop方法。 这是极其缓慢的,我肯定这不是正确的做法:

    def __weighted(self, ds, weights):
      return np.average(ds, weights=weights)
    
    f = {'hours': 'first', 'location_id': 'first', 
    'temp': lambda x: self.__weighted(x, weights), 'prec': lambda x: self.__weighted(x, weights)}
    
    data_frames = []
    for combined_location in all_combined_locations:
       mapped_location_ids = combined_location.location_ids
       weights = combined_location.weights_of_location_ids
       data_for_this_combined_location = pd.concat(df_data.loc[df_data.index.get_level_values(0) == location_id] for location_id in mapped_location_ids)
       data_grouped_by_distance = data_for_this_combined_location.groupby("hours", as_index=False)
       data_grouped_by_distance = data_grouped_by_distance.agg(f)
       data_frames.append(data_grouped_by_distance)
    
    df_combined_location_data = pd.concat(data_frames)
    df_combined_location_data.set_index(['location_id', 'hours'], inplace=True)
    
    
    
    • 这在功能上很好,但是性能和内存消耗很糟糕。 在我的数据集上花费了超过2个小时,这是目前不能接受的。 for循环的存在表明可以更好地处理这个问题。
    • 有没有更好/更快的方法来实现这一点?

  • 共1个答案

    匿名用户

    从我看到的情况来看,您可以使用mapped_location_ids减少一个for循环

    data_for_this_combined_location = df_data.loc[df_data.index.get_level_values(0).isin(mapped_location_ids)]