Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 大熊猫复杂群居_Python_Pandas_Pandas Groupby - Fatal编程技术网

Python 大熊猫复杂群居

Python 大熊猫复杂群居,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,有没有办法使用函数形式的groupby(),例如groupby(f),其中f是一个函数,按表内容分组?它看起来像是用索引调用了f() 样本: import pandas as pd df0 = pd.DataFrame([ dict(age=30,sex='M',name='Jim',weight=143), dict(age=45,sex='F',name='Francine',weight=102), dict(age=22,sex='F',name='Jill',

有没有办法使用函数形式的
groupby()
,例如
groupby(f)
,其中f是一个函数,按表内容分组?它看起来像是用索引调用了
f()

样本:

import pandas as pd

df0 = pd.DataFrame([
    dict(age=30,sex='M',name='Jim',weight=143),
    dict(age=45,sex='F',name='Francine',weight=102),
    dict(age=22,sex='F',name='Jill',weight=190),
    dict(age=37,sex='M',name='Joseph',weight=221),
    dict(age=55,sex='M',name='Jerry',weight=187),
    dict(age=48,sex='M',name='Gus',weight=262),
    dict(age=45,sex='F',name='Jean',weight=112),
    dict(age=28,sex='F',name='Fiona',weight=133),
    dict(age=25,sex='M',name='Greg',weight=165),
    dict(age=34,sex='F',name='Jennifer',weight=137),
    dict(age=26,sex='M',name='Jason',weight=172),
    dict(age=28,sex='M',name='Jerome',weight=205),
    dict(age=61,sex='F',name='Faye',weight=140),
    dict(age=32,sex='M',name='Joshua',weight=180)])
df0.groupby('sex').mean()
这是打印出来的

           age      weight
sex                       
F    39.166667  135.666667
M    35.125000  191.875000

但是,如果我想按性别分组,然后按姓名的第一个字母分组,该怎么办?

尝试使用str访问器,并将索引作为groupby列表中的第二个元素:

df0.groupby(['sex',df0['name'].str[0]]).mean()
输出:

                age      weight
sex name                       
F   F     44.666667  125.000000
    J     33.666667  146.333333
M   G     36.500000  213.500000
    J     34.666667  184.666667

如果需要使用函数,可以创建一个新列:

def get_key(df):
    return df["sex"] + "-" + df["name"].str[0]

df0.assign(my_key=get_key).groupby("my_key").mean()

哇,这很奇怪,所以它注意到我传入了一个具有相同索引值的序列?如果我的处理比一个简单表达式更复杂,那么我需要一个外部函数呢?是的,我认为结果必须与原始数据帧的长度相同。如果索引或长度不匹配,则会出现错误。它必须基于索引进行匹配,因为即使您更改顺序并执行
df0.groupby(['sex',df0.name.str[0].sort_values()).mean()
,答案仍保持不变,但会通过
df0.groupby(['sex',df0.name.str[0].sort_values().reset_index>进行更改(下降=真)]).mean()