2

在 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

我能想到的在 pandas 中执行此操作的方法是使用列表推导而不是任何矢量化 pandas 函数:

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

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

4

2 回答 2

3

You can use groupby, which can apply a function to the index values (in this case looking at the first element):

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
于 2013-09-16T18:31:16.070 回答
2

In pandas v0.12.0 you can convert the Index to a Series and search for the string using str.contains.

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

In v0.13.0 use the Series.filter method:

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

NOTE: The behavior of filter is untested in pandas git master, so I would use it with caution for now. There's an open issue to address this.

于 2013-09-16T18:32:40.557 回答