如何在pandas中找到整体平均值

huangapple go评论61阅读模式
英文:

How to find the overall average in pandas

问题

1 - 类别 DevTool 平均值计算如下

(A 系统的 1 类别 DevTool 计数 + B 系统的 1 类别 DevTool 计数 + ...等)/ 具有 1 类别 DevTool 的系统数量

= (1+2+1+2)/ 4 = 1.5

类似地
0 - 类别 DevTool 平均值计算如下

(A 系统的 0 类别 DevTool 计数 + B 系统的 0 类别 DevTool 计数 + ...等)/ 具有 0 类别 DevTool 的系统数量

= (1+1+2)/ 3 = 1.33

为了执行这个平均值计算,每次我都将数据移到 Excel 并使用 Excel 内置函数来获取这些 1 和 0 类别的平均值。我不确定如何在 pandas 中直接执行这个平均值计算,并获得分别为 1 和 0 类别的平均值 1.5 和 1.33。

英文:

I have a dataframe below:

# initialize list of lists
data = [['A','Excel','1'], ['A','Word_soft','0'],['B','Excel','1'],['B','Word','1'],['C','Word','1'],['C','Word_soft','0'],['D','Java2','1'],['D','Java','1'],['E','PPT','0'], ['E','Word_soft','0']]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['System','App','DevTool'])

I performed the below to get the count of DevTool in each System.

df.groupby(['System','DevTool'])['DevTool'].count()

I need to find the overall DevTool Average in each category 1 and 0 as below

1 - Category DevTool average calculation as below

(A System's 1 category DevTool count + B System's 1 category DevTool count + ...soon) / Number of systems which have 1 category DevTool

= (1+2+1+2) / 4 = 1.5

Similarly
0 - Category Devtool average calculation as below

(A System's 0 category DevTool count + B System's 0 category DevTool count + ...soon) / Number of systems which have 0 category DevTool

= (1+1+2) / 3 = 1.33

In order to perform this average calculation, everytime I move the data to excel and use the excel inbuild function to get this average value. I am not sure how to perform this average calculation within pandas directly and get the average values 1.5 and 1.33 respectively for 1 and 0 category.

答案1

得分: 3

使用 groupby.mean 步骤(.groupby('DevTool').mean()):

(df.groupby(['System','DevTool'])['DevTool'].count()
   .groupby('DevTool').mean()
)

您还可以使用 value_counts 替换第一步:

df[['System','DevTool']].value_counts(sort=False).groupby('DevTool').mean()

输出:

DevTool
0    1.333333
1    1.500000
Name: DevTool, dtype: float64
英文:

Add a groupby.mean step (.groupby('DevTool').mean()):

(df.groupby(['System','DevTool'])['DevTool'].count()
   .groupby('DevTool').mean()
)

You can also replace the first step by value_counts:

df[['System','DevTool']].value_counts(sort=False).groupby('DevTool').mean()

Output:

DevTool
0    1.333333
1    1.500000
Name: DevTool, dtype: float64

huangapple
  • 本文由 发表于 2023年3月9日 16:29:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定