简体   繁体   中英

How to a run function per group that return vector, not single value with pandas?

I want to know, how do I do How to a run function per group that return vector, not single value? in pandas.

I have a dataset with on value-column and on group-column.

   x group order
1 22     a     1
2 33     a     2
3 11     a     3
4  4     b     1
5 88     b     2
6 77     b     3
7 43     b     4
8  9     b     5

I want to analyse value-column per group. For example I want to use an fft. How can I run a function over each group which returns a sequence, not just value (for each group, the fft produces a vector) and get it back as per row.

I expect something like

   y group  order
1 21     a      1
2 62     a      2
3 83     a      3
4  4     a      4
6 46     b      1
7 17     b      2

as output.

I would like to have this done in pandas. Extra points if it can be done with https://github.com/kieferk/dfply

Use apply and wrap the result in a pd.Series

df.groupby('group').x.apply(lambda x: pd.Series(np.random.choice(x, 2)))

group   
a      0    22
       1    33
b      0    88
       1    43
Name: x, dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM