首页 > 解决方案 > 获取数据框中列类别的累积总和

问题描述

我有一个数据框,其中索引是 usergroup1_ids,列名是 usergroup2_ids。数据框的值是来自各个组的用户之间的相似性。例如。

temp_sim_matrix = pd.DataFrame(data = np.random.rand(2,3), columns = ['1', '2', '3'])
print(temp_sim_matrix)

          0         1         2
0  0.982759  0.993010  0.957348
1  0.896425  0.552502  0.455066

现在列名与基于列表的类别相关,其中列名是列表的索引:

column_category = ["A", "B", "A"]

我想生成一个字典,为我提供数据框中每个索引值的每个类别的累积值。像这样:

{0: Counter({'A': 1.9401077624739544,
             'B': 0.9930103537159203}),
 1: Counter({'A': 1.3514912433327915,
             'B': 0.5525021211525775})}

是否有一种有效的 pythonic 方式来做到这一点,因为我目前正在通过迭代数据框中的每一行然后将累积值放入计数器来做到这一点。也许我错过了可以在这里使用的熊猫的一些功能。我的实现是:

row_index_dict = {} # Initializing final dictionary

for index, row in temp_sim_matrix.iterrows(): # Iterating over each row
  cat_counter = Counter() # Creating counter to store cumulative value

  for i in range(len(column_category)): # Loop over columns
    cat_counter[column_category[i]] += row[i] #Add value of row to respective counter key

  row_index_dict[index] = cat_counter #Adding counter to final dictionary

标签: pythonpandasnumpy

解决方案


sum我认为您可以使用 list进行聚合column_category,因为列名的长度相同,然后通过以下方式将其转换为字典DataFrame.to_dict

column_category = ["A", "B", "A"]

d = df.groupby(column_category, axis=1).sum().to_dict('index')
print (d)
{0: {'A': 1.940107, 'B': 0.9930100000000001}, 1: {'A': 1.351491, 'B': 0.552502}}

如果需要Counter使用:

d1 = {k: Counter(v) for k, v in d.items()}

推荐阅读