Pandas group by 将不同的行转换为具有值数组的一行

ig-*_*nyk 3 python group-by dataframe pandas

假设,我们有下一个数据框:

df = pd.DataFrame({'animal': 'cat dog cat fish dog cat cat'.split(),
                  'size': list('SSMMMLL'),
                  'weight': [8, 10, 11, 1, 20, 12, 12],
                  'adult' : [False] * 5 + [True] * 2})

   adult animal size  weight
0  False    cat    S       8
1  False    dog    S      10
2  False    cat    M      11
3  False   fish    M       1
4  False    dog    M      20
5   True    cat    L      12
6   True    cat    L      12
Run Code Online (Sandbox Code Playgroud)

我想通过权重将其转换为以下形式(非规范化):

         weights
animal                 
cat     [8, 11, 12, 12]
dog            [10, 20]
fish                [1]
Run Code Online (Sandbox Code Playgroud)

目前,我使用以下代码:

df.groupby('animal',as_index=True).apply(lambda sf : pd.Series([list(sf['weight'])]
,index=['weights']))
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有明确的方法来做到这一点

mgc*_*mgc 5

这只是比你做的方式略短,但我想你可以做到:

In [22]: df.groupby('animal')['weight'].apply(list)
Out[22]: 
animal
cat     [8, 11, 12, 12]
dog            [10, 20]
fish                [1]
Name: weight, dtype: object
Run Code Online (Sandbox Code Playgroud)

或者

In [40]: df.groupby('animal')['weight'].apply(list).to_frame()
Out[40]: 
                 weight
animal                 
cat     [8, 11, 12, 12]
dog            [10, 20]
fish                [1]
Run Code Online (Sandbox Code Playgroud)

第一个输出 aSeries和第二个 a DataFrame