假设我有以下数据框:
最终输出基本上是每个组的一个数字。我可以通过循环解决问题,但我认为应该有更好的方法?谢谢。
a = np.random.rand(10)
b = np.random.rand(10)*10
c = np.random.rand(10)*100
groups = np.array([1,1,2,2,2,2,3,3,4,4])
df = pd.DataFrame({"a":a,"b":b,"c":c,"groups":groups})
我希望根据组对df进行分组,并将以下函数应用于每个组的两个列(a和b):
def my_fun(x,y):
tmp = np.sum((x*y))/np.sum(y)
return tmp
我尝试的方法是:
df.groupby("groups").apply(my_fun,("a","b"))
但那样做不起作用,会导致错误:
ValueError: Unable to coerce to Series, the length must be 4: given 2
最终输出基本上是每个组的一个数字。我可以通过循环解决问题,但我认为应该有更好的方法?谢谢。