Python DataFrame - groupby和centroid计算

问题描述 投票:3回答:4

我有一个包含两列的数据框:一列包含一个类别,另一列包含一个300维向量。对于Category列中的每个值,我有很多300维向量。我需要的是按类别列对数据帧进行分组,同时获取与每个类别相关的所有向量的质心值。

Category        Vector   
Balance        [1,2,1,-5,....,9]  
Inquiry        [-5,3,1,5,...,10]  
Card           [-3,1,2,3,...1]  
Balance        [1,3,-2,1,-5,...,7]  
Card           [3,1,3,4,...,2]  

所以在上面的例子中,所需的输出是:

Category       Vector   
Balance        [1,2.5,-0.5,-2,....,8]  
Inquiry        [-5,3,1,5,...,10]  
Card           [0,1,2.5,3.5,...,1.5]  

我已经编写了以下函数来获取向量数组并计算其质心:

import numpy as np
    def get_intent_centroid(array):
        centroid = np.zeros(len(array[0]))
        for vector in array:
            centroid = centroid + vector
        return centroid/len(array)    

所以我只需要一个快速的方法来应用上面的函数以及数据帧上的groupby命令。

请原谅我的数据帧格式,但我不知道如何正确格式化它们。

python arrays dataframe centroid
4个回答
2
投票

因此,向量列表的质心只是向量的每个维度的平均值,因此这可以简化为此。

df.groupby('Category')['Vector'].apply(lambda x: np.mean(x.tolist(), axis=0))

它应该比任何循环/列表转换方法更快。


1
投票

根据OP的要求,我有办法通过列表:

vectorsList = list(df["Vector"])
catList = list(df["Category"])

#create a dict for each category and initialise it with a list of 300, zeros
dictOfCats = {}
for each in set(cat):
    dictOfCats[each]= [0] * 300

#loop through the vectorsList and catList
for i in range(0, len(catList)):
    currentVec = dictOfCats[each]
    for j in range(0, len(vectorsList[i])):
        currentVec[j] = vectorsList[i][j] + currentVec[j]
    dictOfCats[each] = currentVec

#now each element in dict has sum. you can divide it by the count of each category
#you can calculate the frequency by groupby, here since i have used only lists, i am showing execution by lists
catFreq = {} 
for eachCat in catList:
    if(eachCat in catList):
        catList[eachCat] = catList[eachCat] + 1
    else:
        catList[eachCat] = 1


for eachKey in dictOfCats:
    currentVec = dictOfCats[eachKey]
    newCurrentVec = [x / catList[eachKey] for x in currentVec]
    dictOfCats[eachKey] = newCurrentVec

#now change this dictOfCats to dataframe again

请注意,代码中可能存在错误,因为我没有使用您的数据进行检查。这将是计算上昂贵的,但如果您无法通过熊猫找出解决方案,那么应该开展工作。如果您确实想出了大熊猫的解决方案,请发布答案


0
投票
import pandas as pd
import numpy as np

df = pd.DataFrame(
    [
        {'category': 'Balance', 'vector':  [1,2,1,-5,9]},
        {'category': 'Inquiry', 'vector': [-5,3,1,5,10]},
        {'category': 'Card', 'vector': [-3,1,2,3,1]},
        {'category': 'Balance', 'vector':  [1,3,-2,1,7]},
        {'category': 'Card', 'vector':  [3,1,3,4,2]}
    ]
)


def get_intent_centroid(array):
    centroid = np.zeros(len(array[0]))
    for vector in array:
        centroid = centroid + vector
    return centroid/len(array)


df.groupby('category')['vector'].apply(lambda x: get_intent_centroid(x.tolist()))

Output:

category
Balance    [1.0, 2.5, -0.5, -2.0, 8.0]
Card         [0.0, 1.0, 2.5, 3.5, 1.5]
Inquiry    [-5.0, 3.0, 1.0, 5.0, 10.0]
Name: vector, dtype: object

0
投票

这应该不使用列表

def get_intent_centroid(array):
    centroid = np.zeros(len(array.iloc[0]))
    for vector in array:
        centroid = centroid + vector
    return centroid/len(array.iloc[0])

df.groupby('Catagory')['Vector'].apply(get_intent_centroid)
© www.soinside.com 2019 - 2024. All rights reserved.