如何基于谓词语句聚合熊猫系列值



在R中,很容易聚合值并应用函数(在本例中为sum

> example <- c(a1=1,a2=2,b1=3,b2=4)
> example # this is the vector (equivalent to Series)
a1 a2 b1 b2 
 1  2  3  4 
> grepl("^a",names(example)) #predicate statement
[1]  TRUE  TRUE FALSE FALSE
> sum(example[grep("^a",names(example))]) #combined into one statement
[1] 3
我能想到的在熊猫

中做到这一点的方法是使用列表理解而不是任何矢量化的熊猫函数:

In [55]: example = pd.Series({'a1':1,'a2':2,'b1':3,'b2':4})
In [56]: example
Out[56]: 
a1    1
a2    2
b1    3
b2    4
dtype: int64
In [63]: sum([example[x] for x in example.index if re.search('^a',x)])
Out[63]: 3

熊猫中是否有与矢量化方法等效的方法?

您可以使用 groupby,它可以将函数应用于索引值(在本例中查看第一个元素):

In [11]: example.groupby(lambda x: x[0]).sum()
Out[11]:
a    3
b    7
dtype: int64
In [12]: example.groupby(lambda x: x[0]).sum()['a']
Out[12]: 3

在 pandas v0.12.0 中,您可以将Index转换为Series并使用 str.contains 搜索字符串。

In [12]: s[s.index.to_series().str.contains('^a')].sum()
Out[12]: 3

在 v0.13.0 中使用 Series.filter 方法:

In [6]: s = Series([1,2,3,4], index=['a1','a2','b1','b2'])
In [7]: s.filter(regex='^a')
Out[7]:
a1    1
a2    2
dtype: int64
In [8]: s.filter(regex='^a').sum()
Out[8]: 3

注意:filter的行为在 pandas git master 中未经测试,所以我现在会谨慎使用它。有一个悬而未决的问题可以解决这个问题。

最新更新