Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

python - how to apply Functions on numpy arrays using pandas groupby function

I'm very new to pandas so I hope this will have an easy answer (and I also appreciate all pointers to even the setup of the dataframe)

So let's say I have the following DataFrame:

D = pd.DataFrame({ i:{ "name":str(i),
                       "vector": np.arange(i,i+10),
                       "sq":i**2,
                       "gp":i%3 } for i in range(10) }).T

    gp  name sq  vector
0    0   0   0   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1    1   1   1   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2    2   2   4   [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
3    0   3   9   [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
4    1   4   16  [4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
5    2   5   25  [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
6    0   6   36  [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
7    1   7   49  [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
8    2   8   64  [8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
9    0   9   81  [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

Now I would like to group by "gp" and get the mean of the "vector"

I've tried

D.groupby('gp').mean()

and even

D.groupby('gp').agg( np.mean )

but I get an error that there were no "numeric types" to be aggregated. So do np.arrays not work in pandas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For me it works:

D.groupby('gp').apply(lambda x: x.vector.mean().mean())

I'm taking the mean twice, since you want the mean group value for the mean of the vector (don't you?).

Out[98]: 
gp
0     9.0
1     8.5
2     9.5
dtype: float64

If you want the mean vector, just take the mean once.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...