Python数据帧有条件地删除重复项
我想根据列的值类型删除数据帧的重复行。例如,我的数据帧是:Python数据帧有条件地删除重复项,python,pandas,dataframe,Python,Pandas,Dataframe,我想根据列的值类型删除数据帧的重复行。例如,我的数据帧是: A B 3 4 3 4 3 5 yes 8 no 8 yes 8 如果df['A']是一个数字,我想删除重复项() 如果df['A']是一个字符串,我想保留重复项 因此,预期的结果将是: A B 3 4 3 5 yes 8 no 8 yes 8 除了对循环使用,还有什么类似python的方法吗?谢谢 创建一个新列C:如果a列是数字列,则在C中指定一个公共值,否则在C中指定一个
A B
3 4
3 4
3 5
yes 8
no 8
yes 8
如果df['A']
是一个数字,我想删除重复项()
如果df['A']
是一个字符串,我想保留重复项
因此,预期的结果将是:
A B
3 4
3 5
yes 8
no 8
yes 8
除了对
循环使用,还有什么类似python的方法吗?谢谢 创建一个新列C
:如果a
列是数字列,则在C
中指定一个公共值,否则在C
中指定一个唯一值
然后,像往常一样,只需删除重复的
注意:有一个很好的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
创建一个新列C
:如果a
列是数字列,则在C
中指定一个公共值,否则在C
中指定一个唯一值
然后,像往常一样,只需删除重复的
注意:有一个很好的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
此解决方案更详细,但对于更复杂的测试可能更灵活:
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])
此解决方案更详细,但对于更复杂的测试可能更灵活:
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])