【问题标题】:Keep one value of a duplicate保留重复的一个值
【发布时间】:2023-01-10 19:40:27
【问题描述】:

我有一个 pandas 数据框,可能有重复值,我想在 ans 列中保留值为 yes 的行

import pandas as pd
import numpy as np

data = {
'id': [1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9, 9, 10],
'ans': ['no', 'yes', 'yes', 'no', 'no', 'yes', 'no', 'yes', 'no', 'no', 'yes', 'no', 'yes', 'no']
}

df = pd.DataFrame(data)
df.head(n = 8)

提前致谢!

【问题讨论】:

  • 你能添加预期的输出吗?

标签: pandas


【解决方案1】:

IIUC 使用:

df = pd.DataFrame(data)
df = df[df['id'].isin(df.loc[df['ans'].eq('yes'), 'id'])]
print (df)
    id  ans
0    1   no
1    1  yes
2    2  yes
5    5  yes
6    5   no
7    6  yes
9    8   no
10   8  yes
11   9   no
12   9  yes

或者:

df = pd.DataFrame(data)
df = df.loc[df['ans'].eq('yes').groupby(df['id']).idxmax()]
print (df)
    id  ans
1    1  yes
2    2  yes
3    3   no
4    4   no
5    5  yes
7    6  yes
8    7   no
10   8  yes
12   9  yes
13  10   no

【讨论】:

  • 这不是有点复杂吗?一个简单的queryloc过滤器就足够了。
  • @bayes2021 - 这取决于需要什么 OP。
【解决方案2】:

你可以使用

df.query("ans=='yes'")

或者

df.loc[df.ans == 'yes',:]

【讨论】:

  • 如果有重复的“是”答案,也许 OP 想删除它们:df.query("ans == 'yes'").drop_duplicates("id")
猜你喜欢
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 2017-07-05
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多