2

我想采用面包屑和频率数组的数据框来查找每个面包屑级别的累积总和。澄清; 面包屑是树中的一系列父子关系,每个节点都有一个关联的频率。树本身并不统一:

pandasdf.A[1] = ['a','b','c','d']
pandasdf.A[2] = ['a','b','c']
pandasdf.A[1] = ['x','y','z','q']
pandasdf.A[2] = ['x','l']
pandasdf.B[1] = 12 # corresponding to 'd'
pandasdf.B[2] = 7 # corresponding to 'c'
pandasdf.B[3] = 2 # corresponding to 'q'
pandasdf.B[4] = 9 # corresponding to 'l'

面包屑是独一无二的(所以我们不必担心重复)。我想得到一个与所有父母孩子的累积总和相对应的系列。即在这种情况下,以pandasdf.A == ['a']19 和pandasdf.A == ['a', 'b']19 为准。

4

1 回答 1

2
import pandas as pd
df = pd.DataFrame({
    'A': [['a','b','c','d'],['a','b','c'],['x','y','z','q'],['x','l']],
    'B': [12,7,2,9]
    })
print(df)

#               A   B
# 0  [a, b, c, d]  12
# 1     [a, b, c]   7
# 2  [x, y, z, q]   2
# 3        [x, l]   9

def cumulative_frequence(df, nodes):
    nodes = set(nodes)
    mask = df['A'].apply(lambda group: not nodes.isdisjoint(group))
    return df.ix[mask, ['B']].sum().item()

print(cumulative_frequence(df, ['a']))
print(cumulative_frequence(df, ['a','b']))
# 19
# 19
于 2013-04-30T23:39:07.333 回答