假设我有以下数据帧,我想删除包含 10 和 100 的行,即在 col1 中只出现过一次的元素。
我可以执行以下操作:
a = df.groupby('col1').size()
b = list(a[a == 1].index)
然后有一个 for 循环并逐行删除行:
d_ind = df[df['col1']==b[0]].index
df.drop(d_ind, axis=0, inplace=True)
有没有更快、更有效的方法?
最佳答案
您可以在col1
上使用duplicated
方法,该方法可以通过keep=False
参数检测元素是否有重复,并返回一个 bool 值您可以使用子集/过滤/删除行的系列:
df[df.col1.duplicated(keep=False)]
# col1 col2 months
#0 1 3 6
#1 1 4 6
#4 4 20 6
#5 4 11 7
#6 4 12 7
关于python - 删除 pandas dataFrame 中给定列中具有唯一元素的行。 (独特是指重复一次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49822414/