python - 匹配一个 ID 中多个列的值

标签 python pandas

示例 DF:

ID     Match1        Match2        Match3     Match4       Match5
1      Yes           No            Yes        Yes          Yes
2      Yes           No            Yes        Yes          No
2      Yes           No            No         Yes          Yes
3      No            Yes           Yes        Yes          No
3      No            Yes           No         No           No
4      Yes           No            Yes        No           No
4      Yes           No            Yes        Yes          Yes

预期的 DF:

 ID     Match1     Match2        Match3     Match4    Match5 Final_Match
    1      Yes      No            Yes        Yes      Yes     Clear
    2      Yes      No            Yes        Yes      No      Unclear
    2      Yes      No            No         Yes      Yes     Unclear
    3      No       Yes           Yes        Yes      No      Clear
    3      No       Yes           No         No       No      Unclear
    4      Yes      No            Yes        No       No      Unclear
    4      Yes      No            Yes        Yes      Yes     Clear

问题陈述:

  1. 如果 ID 不重复,只需将 Clear 放入 Final_Match 列(示例 ID 1)
  2. 如果 ID 是重复的,则在 Match1 到 Match5 列中的 ID 计数 Yes 中,以“Yes”较大者为准,为那个输入 ClearUnclear 另一个(Example ID 3 & 4

  3. 如果 ID 是重复的,则在 Match1 到 Match5 列中的 ID 计数 Yes,如果它们具有相同的“Yes”,则在两者中输入 Unclear(示例编号 2)

我找不到任何关于如何在 ID 内解决的问题?

最佳答案

您还可以通过使用 Groupby.rank 实现此目的:

# Helper Series
s = (df.replace({'Yes': 1, 'No': 0})
     .iloc[:, 1:]
     .sum(1))

df['final_match'] = np.where(s.groupby(df['ID']).rank(ascending=False).eq(1), 'Clear', 'Unclear')

关于python - 匹配一个 ID 中多个列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54888248/

相关文章:

python - 使用 matplotlib 进行连续 3d 绘图

python - 为什么我不能在 Python 的新线程中创建 COM 对象?

python - 如何对不规则时间戳列表进行重采样/下采样?

python - 基于多列对 DataFrame 进行排名

python - 无法解析导入 [Module] (PylancereportMissingImports),模块位于同一文件夹/目录中

python - MapReduce:使用Mrjob在网络图中查找三角形

python - 在qtablewidget中突出显示搜索结果(选择并突出显示该文本或字符而不是所有行或列)

python - 从 github python 下载和访问数据

pandas - 将几列转换为 epoch pandas

python - 根据所有列值在 pandas 中选择一行