在 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
pandas 中是否有等效的矢量化方法?
最佳答案
您可以使用 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 - 如何根据谓词语句聚合 pandas Series 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18834823/