Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.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_Python 3.x_Pandas_Pandas Groupby - Fatal编程技术网

Python 每周一次大熊猫的百分位数?

Python 每周一次大熊猫的百分位数?,python,python-3.x,pandas,pandas-groupby,Python,Python 3.x,Pandas,Pandas Groupby,我需要以下方面的帮助,请提前感谢 我有以下代码按周分组: weekdf = pd.DataFrame(df.groupby(['type', pd.Grouper(key='date', freq='W-SAT')])['id'].count()) 它给了我以下的df: type date id expired 2019-11-09 62 2019-11-16 87 2019-11-23 26 mul

我需要以下方面的帮助,请提前感谢

我有以下代码按周分组:

weekdf = pd.DataFrame(df.groupby(['type', pd.Grouper(key='date', freq='W-SAT')])['id'].count())
它给了我以下的df:

type        date        id  
expired     2019-11-09  62
            2019-11-16  87
            2019-11-23  26
multi       2019-11-09  10
            2019-11-16  14
            2019-11-23  8
single      2019-11-09  296
            2019-11-16  300
            2019-11-23  230
我想要的是有一个df,它能给我每周占总数的百分比

类似于

百分比=每周,过期、多个和单个id的计数/总和:

type        date        id   percent
expired     2019-11-09  62   16.85%
            2019-11-16  87   21.70%
            2019-11-23  26   9.85%
multi       2019-11-09  10   2.72%
            2019-11-16  14   3.49%
            2019-11-23  8    3.03%
single      2019-11-09  296  80.43%
            2019-11-16  300  74.81%
            2019-11-23  230  87.12%
谢谢你的帮助

用于复制数据帧的代码:

l = [{'type': 'expired', 'date': '09-11-2019', 'id': 62},
{'type': 'expired', 'date': '16-11-2019', 'id': 87},
 {'type': 'expired', 'date': '23-11-2019', 'id': 26},
 {'type': 'multi', 'date': '09-11-2019', 'id': 10},
 {'type': 'multi', 'date': '16-11-2019', 'id': 14},
 {'type': 'multi', 'date': '23-11-2019', 'id': 8},
 {'type': 'single', 'date': '09-11-2019', 'id': 296},
 {'type': 'single', 'date': '16-11-2019', 'id': 300},
 {'type': 'single', 'date': '23-11-2019', 'id': 230}]

weekdf = pd.DataFrame(l)
weekdf['date'] = pd.to_datetime(weekdf['date'])
weekdf = weekdf.set_index(['type','date'])
print(weekdf)
您可以使用获取多重索引第一级的值,然后获取周和组:

weekdf['percent'] = (weekdf['id'].div(weekdf.groupby(weekdf.index.get_level_values(-1).week)
                ['id'].transform('sum')).mul(100).round(2).astype(str).add('%'))
print(weekdf)


哇,太谢谢你了!我现在明白了,我一直在为多重索引而挣扎。
                     id percent
type    date                   
expired 2019-09-11   62  16.85%
        2019-11-16   87   21.7%
        2019-11-23   26   9.85%
multi   2019-09-11   10   2.72%
        2019-11-16   14   3.49%
        2019-11-23    8   3.03%
single  2019-09-11  296  80.43%
        2019-11-16  300  74.81%
        2019-11-23  230  87.12%