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

标签 python pandas group-by dataframe

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

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

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

         weights
animal                 
cat     [8, 11, 12, 12]
dog            [10, 20]
fish                [1]

目前,我使用以下代码:

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

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

最佳答案

这只是比你做的方式稍微短一点,但我想你可以做到:

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

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

第一个输出一个Series,第二个输出一个DataFrame

关于python - Pandas group by 将不同的行转换为具有值数组的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143988/

相关文章:

python - scrapy没有给出任何输出

python - 如何解压内部包含 tar.gz 文件的 tar 文件目录?

Python 请求,在访问 API 时不断出现 401 错误

python - 如何在每个列都有系列的DataFrame上进行操作

python - 多索引数据框删除每组最大值的行

Mysql合并统计多列

python - 四舍五入字典中的浮点值

python - 如何使用字符串列表通过 Python 3 搜索 Pandas 数据框

MYSQL:从多列中选择最大日期

每组 SQL 不同值 - 如何 "group by"并获取每组不同值的列表?