Python 删除列中的重复值,保留行
我有一个类似于删除重复项的问题,但我需要保留具有重复值的行。所以本质上,我需要保留第一个值,然后用“”替换它的每个重复 我需要的是:Python 删除列中的重复值,保留行,python,pandas,Python,Pandas,我有一个类似于删除重复项的问题,但我需要保留具有重复值的行。所以本质上,我需要保留第一个值,然后用“”替换它的每个重复 我需要的是: Col1 Col2 a 1 b c d 2 谢谢。使用with replace values可清空字符串-但得到混合值-数值与字符串,因此某些函数可能会失败。更好的方法是替换为NaNs,尽管integers转换为floats df.loc[df['Col2'].duplicated(), 'Col2'] = '' #if
Col1 Col2
a 1
b
c
d 2
谢谢。使用with replace values可清空字符串-但得到混合值-数值与字符串,因此某些函数可能会失败。更好的方法是替换为NaN
s,尽管integer
s转换为float
s
df.loc[df['Col2'].duplicated(), 'Col2'] = ''
#if want numeric column
#df.loc[df['Col2'].duplicated(), 'Col2'] = np.nan
更快的选择:
df['Col2'] = np.where(df['Col2'].duplicated(), '', df['Col2'])
确实如此,但建议使用groupby不是更好吗?这本质上就是OP想要的?@DeepSpace-
groupby
是一个不错的选择,但作为复制的矢量化解决方案,它仍然比较慢。
df['Col2'] = np.where(df['Col2'].duplicated(), '', df['Col2'])
print (df)
Col1 Col2
0 a 1
1 b
2 c
3 d 2