How does the pandas groupby method work?

So, I tried to understand the function pandas.dataFrame.groupby (), and I came across this example in the documentation:

    In [1]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
   ...:                           'foo', 'bar', 'foo', 'foo'],
   ...:                    'B' : ['one', 'one', 'two', 'three',
   ...:                           'two', 'two', 'one', 'three'],
   ...:                    'C' : np.random.randn(8),
   ...:                    'D' : np.random.randn(8)})
   ...: 

In [2]: df
Out[2]: 
     A      B         C         D
0  foo    one  0.469112 -0.861849
1  bar    one -0.282863 -2.104569
2  foo    two -1.509059 -0.494929
3  bar  three -1.135632  1.071804
4  foo    two  1.212112  0.721555
5  bar    two -0.173215 -0.706771
6  foo    one  0.119209 -1.039575
7  foo  three -1.044236  0.271860

In order not to research, I did this:

print(df.groupby('B').head())

it outputs the same data file, but when I do this:

print(df.groupby('B'))

this gives me the following:

<pandas.core.groupby.DataFrameGroupBy object at 0x7f65a585b390>

What does it mean? In regular data printing, it .head()simply prints the first 5 lines, what happens here?

And also why printing .head()gives the same result as a dataframe? Should I group column items 'B'?

+3
source share
1 answer

When you use only

df.groupby('A')

groupby. . , , groupby :

  • (, DataFrame) DataFrames
  • (, ) Series.

:

df = DataFrame({'A' : [1, 1, 2, 2], 'B' : [1, 2, 3, 4]})
grouped = df.groupby('A')

# each `i` is a tuple of (group, DataFrame)
# so your output here will be a little messy
for i in grouped:
    print(i)
(1,    A  B
0  1  1
1  1  2)
(2,    A  B
2  2  3
3  2  4)

# this version uses multiple counters
# in a single loop.  each `group` is a group, each
# `df` is its corresponding DataFrame
for group, df in grouped:
    print('group of A:', group, '\n')
    print(df, '\n')
group of A: 1 

   A  B
0  1  1
1  1  2 

group of A: 2 

   A  B
2  2  3
3  2  4 

# and if you just wanted to visualize the groups,
# your second counter is a "throwaway"
for group, _ in grouped:
    print('group of A:', group, '\n')
group of A: 1 

group of A: 2 

.head. docs :

.apply(lambda x: x.head(n))

, groupby. , .head(5) ( DataFrame), , 5 , DataFrame.

. .head(1), 1 :

print(df.groupby('A').head(1))
   A  B
0  1  1
2  2  3
+8

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


All Articles