gpt4 book ai didi

python - Pandas 使用双重条件删除重复项

转载 作者:行者123 更新时间:2023-12-01 01:37:05 26 4
gpt4 key购买 nike

考虑以下 DF

    import pandas as pd
df = pd.DataFrame({'ID': [1,1,1,1,2,2,2,2],
'Course':
['English','English','English','History','Science', 'Science', 'Science','Math'],
'Status':
['Attended', 'Requested', 'Partially Attended', 'No show',
'Requested','Attended','Partially Attended','No show']})
df.set_index(['ID'])
print(df)

Course Status
ID
1 English Attended
1 English Requested
1 English Partially Attended
1 History No show
2 Science Requested
2 Science Attended
2 Science Partially Attended
2 Math No show

我正在尝试根据以下 3 个假设找到一种删除重复项的方法。

  1. ID 出现多次。
  2. 如果 ID 多次出现,则类(class)必须相同。 (所以 1、历史和 2、数学可以保留)
  3. 如果找到匹配项,那么我只想删除类(class)已完成且存在请求的实例,删除包含请求的行。缺席和部分出席都可以。

我目前正在学习和参加 DataCamps Python 和 pandas 类(class),因此我熟悉 groupby、聚合、排序函数,在这些函数中我可以删除时间序列数据中较晚或较早的重复项。我不知道如何将条件或逻辑应用于放置函数。我在这个论坛上搜索过类似的功能,但我还没有将任何东西应用到我自己的 DF 上。

我想要的结果如下:

Course  Status
ID
1 English Attended
1 English Partially Attended
1 History No show
2 Science Attended
2 Science Partially Attended
2 Math No show

最佳答案

重复或未请求

df[~df.duplicated(['ID', 'Course'], keep=False) | df.Status.ne('Requested')]

Course ID Status
0 English 1 Attended
2 English 1 Partially Attended
3 History 1 No show
5 Science 2 Attended
6 Science 2 Partially Attended
7 Math 2 No show
<小时/>

pandas.DataFrame.duplicated

识别事物是否重复。我传递了一个列名称列表来用于确定重复性。通过使用 keep=False,我指定要将第一次或最后一次出现的情况也算作重复项。

df.duplicated(['ID', 'Course'], keep=False)

0 True
1 True
2 True
3 False
4 True
5 True
6 True
7 False
dtype: bool

但是,如果它是重复的,还要检查它是否是请求的

df.Status.ne('Requested')

0 True
1 False
2 True
3 True
4 False
5 True
6 True
7 True
Name: Status, dtype: bool

因此,我们希望行不重复,并且至少不具有等于 RequestedStatus

关于python - Pandas 使用双重条件删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52303467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com