pandas数组的条件累积和

时间:2013-04-30 22:22:50

标签: python pandas

我想获取面包屑和频率数组的数据框,以找到面包屑每个级别的累积总和。澄清;面包屑是树中的一系列父子关系,每个节点具有相关的频率。树本身并不统一:

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。

1 个答案:

答案 0 :(得分: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