【问题标题】:if condition within groupby pandas如果在 groupby pandas 中的条件
【发布时间】:2021-02-10 12:45:26
【问题描述】:

计算target 列,其中默认值为1,但当ID1 中的组具有Yes 时,它为0,因此例如在9 中有一个值为Yes 我们想要将其他No 保留为0
给定目标 col 是预期的答案

ID1 ID2 Match target
4   A10 Yes   1
4   A20 No    0
5   A30 Yes   1
6   A50 No    1
6   A60 No    1
7   A70 Yes   1
8   A60 No    1
9   A30 Yes   1
9   A20 No    0
9   A10 No    0

【问题讨论】:

  • 有一点模棱两可的问题。所以,基本上你是想把每一个yes映射到1,把no映射到0吗?目标列是您所期望的吗?
  • 是的,给定的目标列是预期的答案。 “否”为 1,如果 ID1 列中为 6,因为 6 没有“是”

标签: python pandas numpy data-manipulation


【解决方案1】:

对于只有No 值的测试组,您可以使用Series.eqGroupBy.transformGroupBy.all 进行比较:

m1 = df['Match'].eq('No').groupby(df['ID1']).transform('all')
#or test not equal Yes
m1 = df['Match'].ne('Yes').groupby(df['ID1']).transform('all')
#alternative
#m1 = ~df['ID1'].isin(df.loc[df['Match'].ne('No'), 'ID1'])
m2 = df['Match'].eq('Yes')

df['target1'] = (m1 | m2).view('i1')
print (df)
   ID1  ID2 Match  target  target1
0    4  A10   Yes       1        1
1    4  A20    No       0        0
2    5  A30   Yes       1        1
3    6  A50    No       1        1
4    6  A60    No       1        1
5    7  A70   Yes       1        1
6    8  A60    No       1        1
7    9  A30   Yes       1        1
8    9  A20    No       0        0
9    9  A10    No       0        0

【讨论】:

    猜你喜欢
    • 2021-09-13
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2019-08-10
    • 1970-01-01
    • 2017-12-18
    • 2021-04-30
    相关资源
    最近更新 更多