Including group name in apply pandas python function

Discard the group call name use the group name in the applicable lambda function.

For example, if I iterate over groups, I can get the group key through the following tuple parsing:

for group_name, subdf in temp_dataframe.groupby(level=0, axis=0):
    print group_name

to get the group name in the apply function, for example:

temp_dataframe.groupby(level=0,axis=0).apply(lambda group_name, subdf: foo(group_name, subdf)

How to get the group name as an argument to use the lambda function?

Thanks!

+11
source share
2 answers

I think you should use the attribute name:

temp_dataframe.groupby(level=0,axis=0).apply(lambda x: foo(x.name, x))

should work, for example:

In [132]:
df = pd.DataFrame({'a':list('aabccc'), 'b':np.arange(6)})
df

Out[132]:
   a  b
0  a  0
1  a  1
2  b  2
3  c  3
4  c  4
5  c  5

In [134]:
df.groupby('a').apply(lambda x: print('name:', x.name, '\nsubdf:',x))

name: a 
subdf:    a  b
0  a  0
1  a  1
name: b 
subdf:    a  b
2  b  2
name: c 
subdf:    a  b
3  c  3
4  c  4
5  c  5
Out[134]:
Empty DataFrame
Columns: []
Index: []
+19
source

For those who came in search of an answer to the question:

pandas python

, , .

:

df = pd.DataFrame(data={'col1': list('aabccc'),
                        'col2': np.arange(6),
                        'col3': np.arange(6)})

:

    col1    col2    col3
0   a       0       0
1   a       1       1
2   b       2       2
3   c       3       3
4   c       4       4
5   c       5       5

( apply) :

df.groupby('a') \
.apply(lambda frame: frame \
       .transform(lambda col: col + 3 if frame.name == 'a' and col.name == 'b' else col))

:

    col1    col2    col3
0   a       3       0
1   a       4       1
2   b       2       2
3   c       3       3
4   c       4       4
5   c       5       5

, , sub pandas.core.frame.DataFrame ( frame), name . (.. ) /.

, , , , :

for grp_name, sub_df in df.groupby('col1'):
    for col in sub_df:
        if grp_name == 'a' and col == 'col2':
            df.loc[df.col1 == grp_name, col] = sub_df[col] + 3

, . , pandas, , , , .

0

Source: https://habr.com/ru/post/1606434/


All Articles