社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python中一个wrt另一个wrt或averageIf的平均值

Gangadhar Dixit • 3 年前 • 1576 次点击  

enter image description here

我有一个熊猫df显示,我想计算 按品牌划分的DC平均费率 与excel中的averageif类似的列, 我尝试过groupby mean()之类的方法,但没有给出正确的结果

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131164
 
1576 次点击  
文章 [ 2 ]  |  最新文章 3 年前
sophocles
Reply   •   1 楼
sophocles    3 年前

AVERAGEIF 在excel中,返回与原始数据大小相同的列。所以我觉得你在找 pandas.transform() :

# Sample DF

   Brand  Rate
0      A    45
1      B   100
2      C    28
3      A    92
4      B     2
5      C    79
6      A    48
7      B    97
8      C    72
9      D    14
10     D    16
11     D    64
12     E    85
13     E    22

结果:

df['Avg Rate by Brand'] = df.groupby('Brand')['Rate'].transform('mean')

print(df)

   Brand  Rate  Avg Rate by Brand
0      A    45          61.666667
1      B   100          66.333333
2      C    28          59.666667
3      A    92          61.666667
4      B     2          66.333333
5      C    79          59.666667
6      A    48          61.666667
7      B    97          66.333333
8      C    72          59.666667
9      D    14          31.333333
10     D    16          31.333333
11     D    64          31.333333
12     E    85          53.500000
13     E    22          53.500000
enke
Reply   •   2 楼
enke    3 年前

你的问题不清楚,但你可能在寻找:

df.groupby(['DC','Brand'])['Rate'].mean()