[英]Pandas percentage of two columns
I have a data frame that looks like this:我有一个看起来像这样的数据框:
Vendor GRDate Pass/Fail
0 204177 2022-22 1.0
1 204177 2022-22 0.0
2 204177 2022-22 0.0
3 204177 2022-22 1.0
4 204177 2022-22 1.0
5 204177 2022-22 1.0
7 201645 2022-22 0.0
8 201645 2022-22 0.0
9 201645 2022-22 1.0
10 201645 2022-22 1.0
I am trying to work out the percentage of where Pass/Fail equals 1 for each week for each vendor and put it in a new df (Number of pass = 1 / total number of lines per vendor & week)我正在尝试计算每个供应商每周通过/失败等于 1 的百分比,并将其放入新的 df(通过数 = 1 / 每个供应商和每周的总行数)
which would look like this:看起来像这样:
Vendor GRDate Performance
0 204177 2022-22 0.6
1 201645 2022-22 0.5
I'm trying to do this with .groupby()
and .count()
but i can't work out how to get this into a new df along with the Vendor and GRDate columns.我正在尝试使用
.groupby()
和 .count( .count()
来执行此操作,但我不知道如何将其与 Vendor 和 GRDate 列一起放入新的 df 中。 The code I have here returns the percentage of pass fail but drops the other two columns.我这里的代码返回通过失败的百分比,但删除其他两列。
sdp_percent = sdp.groupby(['GRDate','Vendor'])['Pass/Fail'].apply(lambda x: x[x == 1].count()) / sdp.groupby(['GRDate','Vendor'])['Pass/Fail'].count()
But then if I add .reset_index()
to keep them I get this error: unsupported operand type(s) for /: 'str' and 'str'但是如果我添加
.reset_index()
来保留它们,我会得到这个错误:unsupported operand type(s) for /: 'str' and 'str'
Please can someone explain what i'm doing wrong?请有人可以解释我做错了什么吗?
Try:尝试:
x = (
df.groupby(["GRDate", "Vendor"])["Pass/Fail"]
.mean()
.reset_index()
.rename(columns={"Pass/Fail": "Performance"})
)
print(x)
Prints:印刷:
GRDate Vendor Performance
0 2022-22 201645 0.500000
1 2022-22 204177 0.666667
As you have 0/1, you can use a groupby.mean
:因为你有 0/1,你可以使用
groupby.mean
:
(df.groupby(['Vendor', 'GRDate'], as_index=False, sort=False)
.agg(Performance=('Pass/Fail', 'mean'))
)
If you had a specific arbitrary value X
:如果你有一个特定的任意值
X
:
(df.assign(val=df['Pass/Fail'].eq(X))
.groupby(['Vendor', 'GRDate'], as_index=False, sort=False)
.agg(Performance=('val', 'mean'))
)
Output: Output:
Vendor GRDate Performance
0 204177 2022-22 0.666667
1 201645 2022-22 0.500000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.