我希望根据列的值类型,删除数据type的重复行。例如,我的数据文件是:
A B
3 4
3 4
3 5
yes 8
no 8
yes 8如果df['A']是一个数字,我想要drop_duplicates()。
如果df['A']是一个字符串,我希望保留副本。
因此,预期的结果将是:
A B
3 4
3 5
yes 8
no 8
yes 8除了使用for循环之外,还有Pythonic的方法吗?谢谢!
发布于 2015-10-20 15:05:53
创建一个新的列C:如果A列是数字的,那么在C中分配一个公共值,否则在C中分配一个唯一的值。
在那之后,drop_duplicates就像平常一样。
注意:有一个很好的isnumeric()方法来测试单元格是否类似于数字。
In [47]:
df['C'] = np.where(df.A.str.isnumeric(), 1, df.index)
print df
A B C
0 3 4 1
1 3 4 1
2 3 5 1
3 yes 8 3
4 no 8 4
5 yes 8 5
In [48]:
print df.drop_duplicates()[['A', 'B']] #reset index if needed
A B
0 3 4
2 3 5
3 yes 8
4 no 8
5 yes 8发布于 2015-10-20 15:15:38
这个解决方案更冗长,但对于更复杂的测试可能更灵活:
def true_if_number(x):
try:
int(x)
return True
except ValueError:
return False
rows_numeric = df['A'].apply(true_if_number)
df['A'][rows_numeric].drop_duplicates().append(df['A'][~rows_numeric])https://stackoverflow.com/questions/33239863
复制相似问题