Problem

很抱歉,所有帮助过我的人,但我不得不重新措辞这个问题.我有一个数据帧,其中包含除最后一列以外的大多数列的重复项.在有重复项的情况下,我想应用以下规则:

  1. 如果最后一列中的两个条目都有效,则两个都保留.
  2. 如果最后一列中的两个条目都为空,则保留一个.
  3. 如果一个条目有效,另一个条目为空,则保留有效条目.

然后,我想取出重复的值,并用它们创建一个单独的数据帧.目前,我的方法很费力,会删除两个都为空的重复项.

Reprex

100

import pandas as pd
import numpy as np

data_input = {'Student':     ['A', 'A',          'B', 'B',            'C',      'D',      'E',      'F', 'F',         'G',     "H",     "H", "I", "I"], 
              "Subject": ["Law", "Law",      "Maths", "Maths",    "Maths", "Law",    "Maths",  "Music", "Music", "Music",      "Art", "Art", "Dance", "Dance"], 
              "Checked":  ["Bob", "James",    np.nan,  "Jack",     "Laura", "Laura",  np.nan,    np.nan, "Tim",   "Tim",       "Tim", np.nan, np.nan, np.nan]}

# Create DataFrame
df1 = pd.DataFrame(data_input)

enter image description here

100

enter image description here

100

attempt1 = df1.sort_values(['Student', 'Checked'], ascending=False).drop_duplicates(["Student", "Subject"]).sort_index()

这是我从Stack上的另一个Q&Amp;A中拿来的,但它没有给我我想要的结果,我也不明白.

100

#Create Duplicate column
df1["Duplicates"] = df1.duplicated(subset=["Student", "Subject"], keep=False)

#Create list of rows with no duplicates
df_new1 = df1[df1["Duplicates"]==False]

#Create list of rows with duplicates & remove all those with null values
#HERE IS WHERE I GET STUCK. IF BOTH DUPLICATES ARE NULLS, I WANT TO KEEP ONE OF THEM
df_new2 = df1[df1["Duplicates"]==True]
df_new3 = df_new2[~df_new2["Checked"].isnull()]

#Combine unique rows, and duplicates without null values
#Keep duplicates without null values
df_new = df_new1.append(df_new3)

#Tidy up
df_new = df_new[["Student", "Subject", "Checked"]].sort_values(by="Student")

df_new

100

#Create separate list of duplicates with valid "Checked" values
df_new["Duplicates"] = df_new.duplicated(subset="Student", keep=False)
conflicting_duplicates = df_new[df_new["Duplicates"]==True]
conflicting_duplicates

100

谢谢大家!您的回答有帮助,但我没有意识到我还想保留其中一个条目,其中两个条目都为空.

有没有更好的方法来做这件事?

推荐答案

使用布尔索引:

# is the group containing more than one row?
m1 = df1.duplicated(['Student', 'Subject'], keep=False)
# is the row a NaN in "Checked"?
m2 = df1['Checked'].isna()
# both conditions True
m = m1&m2

# keep if either condition is False 
df1[~m]

# to get dropped duplicates
# keep if both are True
df1[m]

输出:

   Student Subject Checked
0        A     Law     Bob
1        A     Law   James
3        B   Maths    Jack
4        C   Maths   Laura
5        D     Law   Laura
6        E   Maths     NaN
8        F   Music     Tim
9        G   Music     Tim
10       H     Art     Tim

Python相关问答推荐

使用FASTCGI在IIS上运行Django频道

比较2 PD.数组的令人惊讶的结果

Pandas 都是(),但有一个门槛

当独立的网络调用不应该互相阻塞时,'

运输问题分支定界法&

为什么抓取的HTML与浏览器判断的元素不同?

如何从数据库上传数据到html?

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

使用BeautifulSoup抓取所有链接

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?

通过追加列表以极向聚合

如何按row_id/row_number过滤数据帧

pandas fill和bfill基于另一列中的条件

用fft计算指数复和代替求和来模拟衍射?

Django在一个不是ForeignKey的字段上加入'

使用pythonminidom过滤XML文件

将数据从一个单元格保存到Jupyter笔记本中的下一个单元格

try 在单个WITH_COLUMNS_SEQ操作中链接表达式时,使用Polars数据帧时出现ComputeError

如何更改网络中某条边的位置(&Q;)?