删除行:与其他列不匹配

时间:2019-04-10 05:25:21

标签: pandas csv

我有一个如下所示的数据框:

Type    Brand A Brand B
Type A  ID A    ID AA
Type B  ID A    ID AA
Type A  ID B    ID BB
Type B  ID B    ID BB
Type B  ID C    ID CC
Type A  ID C    ID DD
Type B  ID D    ID EE
Type A  ID D    ID FF

我要删除或消除行数据两个品牌列和ype列(必须是一对)

我的愿望结果如下:

Type    Brand A Brand B
Type A  ID A    ID AA
Type B  ID A    ID AA
Type A  ID B    ID BB
Type B  ID B    ID BB

先谢谢您

1 个答案:

答案 0 :(得分:3)

您可以通过SeriesGroupBy.nunique测试唯一值的数量,也可以通过每组DataFrameGroupBy.size来计算唯一值的数量是否是对(2):

g = df.groupby(['Brand A','Brand B'])['Type']
df = df[g.transform('nunique').eq(2) & g.transform('size').eq(2)]
print (df)
     Type Brand A Brand B
0  Type A    ID A   ID AA
1  Type B    ID A   ID AA
2  Type A    ID B   ID BB
3  Type B    ID B   ID BB

如果需要测试Type AType B

g = df.groupby(['Brand A','Brand B'])['Type']
df = df[g.transform(lambda x: set(x) == set(['Type A','Type B'])) & g.transform('size').eq(2)]
print (df)
     Type Brand A Brand B
0  Type A    ID A   ID AA
1  Type B    ID A   ID AA
2  Type A    ID B   ID BB
3  Type B    ID B   ID BB
相关问题