Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.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,我有一个带有两列ID和标签的数据框。标签只能为0或1 下面的代码生成这样一个数据帧 数据=[[10105,1],[10105,1],[10105,0],[20205,0],[20205,0],[20205,1],[20205,1]] test=pd.DataFramedata,columns=[ID,label] 测验 ID标签 0 10105 1 1 10105 1 2 10105 0 3 20205 0 4 20205 0 5 2

我有一个带有两列ID和标签的数据框。标签只能为0或1

下面的代码生成这样一个数据帧

数据=[[10105,1],[10105,1],[10105,0],[20205,0],[20205,0],[20205,1],[20205,1]] test=pd.DataFramedata,columns=[ID,label] 测验 ID标签 0 10105 1 1 10105 1 2 10105 0 3 20205 0 4 20205 0 5 20205 1 6 20205 1 一旦数据按ID分组,我想获得一些关于标签的统计信息

test.groupby'ID' 将按ID对条目进行分组,但我想看看有多少ID为10105的条目的标签为1,有多少条目的标签为0。我还想计算0的百分比。那将是理想的输出

ID 10105,label1:2,label0:1,Percantage label0/label1+label0:1/3 ID 20205,label1:2,label0:2,Percantage label0/label1+label0:2/4 我认为python有一种聚合结果的方法,但同时我需要一种在特定ID的标签之间进行计算的方法

你能帮帮我吗

我想提前感谢您的回复

问候 Alex

您可以将元组用于具有聚合函数的新列名-对于label0和Percantage,将值按0进行比较,并按总和进行计数,平均值为百分比。它正在工作,因为Trues的处理方式与1类似

如果使用0.25+:

def label0(x):
    return x.eq(0).sum()

def Percantage(x):
    return x.eq(0).mean()


df = test.groupby('ID').agg(label1=pd.NamedAgg(column='label', aggfunc='sum'),
                            label0=pd.NamedAgg(column='label', aggfunc=label0),
                            Percantage=pd.NamedAgg(column='label', aggfunc=Percantage))
索引中的最后一列(如果需要):

df = df.reset_index()
print (df)

      ID  label1  label0  Percantage
0  10105       2       1    0.333333
1  20205       2       2    0.500000
使用:


@我不知道你能把一个系列按另一个栏目分组。整洁

谢谢。然后我如何才能找到有多少个条目具有0或1个百分比?这将给出类似于纯ID的东西,它至少只有0或1percentage@AlexP-您可以使用df=test.groupby'ID'['label'].agg['label1'、'sum'、'label0',λx:x.eq0.sum,'percantie0',λx:x.eq0.mean,'percantia1',λx:x.mean]我是否可以使用类似的概念来选择所有具有至少两倍相同ID的行。因此,不要选择ID只出现一次的行。@AlexP-您可以检查solution.df=df[df.duplicatedsubset=['ID',keep=False]
df = df.reset_index()
print (df)

      ID  label1  label0  Percantage
0  10105       2       1    0.333333
1  20205       2       2    0.500000
>>> test['label'].groupby(test['ID']).value_counts(normalize=True)
ID     label
10105  1        0.666667
       0        0.333333
20205  0        0.500000
       1        0.500000
Name: label, dtype: float64