【问题标题】:How is pandas groupby method actually working?pandas groupby 方法实际上是如何工作的?
【发布时间】:2023-03-25 04:40:01
【问题描述】:

所以我试图理解 pandas.dataFrame.groupby() 函数,我在文档中遇到了这个例子:

    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

为了进一步探索,我这样做了:

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

它输出相同的数据帧,但是当我这样做时:

print(df.groupby('B'))

它给了我这个:

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

这是什么意思?在普通的 dataFrame 中打印 .head() 只是输出前 5 行这里发生了什么?

还有为什么打印.head() 会提供与数据框相同的输出?不应该按'B'列的元素分组吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    当你使用时

    df.groupby('A')
    

    你会得到一个GroupBy object。那时您还没有对其应用任何功能。在后台,虽然这个定义可能并不完美,但您可以将groupby 对象视为:

    • (group, DataFrame) 对的迭代器,用于 DataFrame,或
    • (group, Series) 对的迭代器,用于 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
    

    【讨论】:

      猜你喜欢
      • 2012-12-08
      • 2021-01-21
      • 2011-09-27
      • 2021-12-16
      • 2013-03-14
      • 2021-03-23
      • 2011-02-11
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多