【问题标题】:in pandas, calculate product of row values in a column (which are grouped by a category) and assign the product value to all rows in each group?在熊猫中,计算列中行值的乘积(按类别分组)并将乘积值分配给每组中的所有行?
【发布时间】:2018-05-12 16:56:11
【问题描述】:

我的数据框 df 有 3 列 “零件”:零件编号 “测试”:测试名称 'test_pass':每个测试的通过或失败结果。1是通过,0是失败。

我想创建第四列“part_pass”。 对于任何“部分”,如果至少有一个“测试通过”等于 0,则该“部分”是失败的部分。对于那部分,我想让“part_pass”对于该“部分”的所有行都等于 0。

对于任何“part”,如果所有“test_pass”都等于1,则该“part”为通过部分。对于那部分,我想让“part_pass”对于该“部分”的所有行都等于 1。

如何计算按“part”分组的“test_pass”的乘积,并将结果值按部分组分配给“part_pass”的行?

【问题讨论】:

  • 不要发布图片。发布代码以轻松重现您的数据集
  • 抱歉,这是我第一次尝试在 Stackoverflow 上提问。下一次,我会确保包含代码,而不是图像。

标签: python pandas


【解决方案1】:

重现数据集的代码:

df = pd.DataFrame()
df["part"] = [1,2,3,1,2,3,1,2,3]
df["test"] = ["test1"]*3 + ["test2"]*3 + ["test3"]*3
df["test_pass"] = [1,1,0,1,1,1,1,1,1]

part    test    test_pass
0   1   test1   1
1   2   test1   1
2   3   test1   0
3   1   test2   1
4   2   test2   1
5   3   test2   1
6   1   test3   1
7   2   test3   1
8   3   test3   1

您需要以下逻辑(几乎是您得到的,但使用索引):

df2 = df.set_index("part")
df2["part_pass"] = df.groupby("part")["test_pass"].prod()
df2 = df2.reset_index()


part    test    test_pass   part_pass
0   1   test1   1           1
1   2   test1   1           1
2   3   test1   0           0
3   1   test2   1           1
4   2   test2   1           1
5   3   test2   1           0
6   1   test3   1           1
7   2   test3   1           1
8   3   test3   1           0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2021-10-14
    相关资源
    最近更新 更多