基于多个列(可能包括多个值)标识duplicate,如果在python中标识为duplicate,则返回Boolean
这是一个相当简单的查询,但我没有找到任何相关的解决方案。我必须根据多个列来识别重复项。扭曲之处在于,一个列在一行中可以有多个值,需要将其视为单独的值 例如:基于多个列(可能包括多个值)标识duplicate,如果在python中标识为duplicate,则返回Boolean,python,pandas,duplicates,Python,Pandas,Duplicates,这是一个相当简单的查询,但我没有找到任何相关的解决方案。我必须根据多个列来识别重复项。扭曲之处在于,一个列在一行中可以有多个值,需要将其视为单独的值 例如: dct ={'store':('A','A','A','A','A','B','B','B','C','C','C','C'), 'station':('aisle','aisle','aisle','window','window','aisle','aisle','aisle','aisle','window','window
dct ={'store':('A','A','A','A','A','B','B','B','C','C','C','C'),
'station':('aisle','aisle','aisle','window','window','aisle','aisle','aisle','aisle','window','window','window'),
'produce':('apple','apple','cherry, apple','orange','orange','apple','apple,orange','orange','apple','apple','apple','orange')}
df = pd.DataFrame(dct)
print(df)
store station produce
0 A aisle apple
1 A aisle apple
2 A aisle cherry, apple
3 A window orange
4 A window orange
5 B aisle apple
6 B aisle apple,orange
7 B aisle orange
8 C aisle apple
9 C window apple
10 C window apple
11 C window orange
预期数据帧:
store station produce result
A aisle apple False
A aisle apple False
A aisle cherry,apple False
A window orange True
A window orange True
B aisle apple False
B aisle apple,orange False
B aisle orange False
C aisle apple True --> not duplicated; 'station' is diff
C window apple False
C window apple False
C window orange True
我一直在使用df.duplicated(subset=['store'、'station'、'product'],keep=False)
但是它丢失了一行中包含多个值的数据,知道如何解决吗?可选添加: 类似的功能,如“keep”(确定要标记的重复项(如果有))first/last/false
最后一部分是完全可选的,不是必须的:-)您可以使用
series.str.split
创建唯一产品的列表,并df.explode
根据需要添加新行,然后检查重复项
df.produce = df.produce.str.split(',')
df = df.explode('produce')
df['result'] = df.duplicated(
subset=['store', 'station', 'produce'],
keep=False)
输出
store station produce result
0 A aisle apple True
1 A aisle apple True
2 A aisle cherry False
2 A aisle apple False
3 A window orange True
4 A window orange True
5 B aisle apple True
6 B aisle apple True
6 B aisle orange True
7 B aisle orange True
8 C aisle apple False
9 C window apple True
10 C window apple True
11 C window orange False
让我们做吧
df['New'] = df.assign(produce=df['produce'].str.split(', ')).\
explode('produce').\
duplicated(subset=['store', 'station', 'produce'], keep=False).any(level=0)
Out[160]:
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 True
8 False
9 True
10 True
11 False
dtype: bool
为了清楚起见,副本被标记为
False
?是的,False是好的。