我有一个数据框,我正在try 使用group-by删除重复项.
data = {
'Type': ['A', 'B', 'B', 'B', 'B', 'B', 'B', 'C', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'C','D','D'],
'Key': ['ZPOC', 'adr#', 'name#', 'city#', 'adr#', 'city#', 'city#', 'ZZRE', 'ZPOC', 'adr#', 'name#', 'city#', 'adr#', 'city#', 'city#', 'ZZRE','item','item']
}
df = pd.DataFrame(data)
在类型列中,您可以看到该行从‘A’开始.因此,在下一个‘A’出现之前,它是我的一个团队.从该组中,我希望根据键列中的值保留最后出现的行,从而删除重复的行.
因此,只考虑第一组(A-B-C).在该组中,ADR#和CITY#重复出现两次,因此我希望仅从该重复项中保留最后一次出现.这一进程应针对每一组继续进行.
Note the duplicate rows should be removed only where Type = 'B'个
我几乎得到了我想要的输出,但过滤在Type=‘B’上不起作用
import pandas as pd
data = {
'Type': ['A', 'B', 'B', 'B', 'B', 'B', 'B', 'C', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'C','D','D'],
'Key': ['ZPOC', 'adr#', 'name#', 'city#', 'adr#', 'city#', 'city#', 'ZZRE', 'ZPOC', 'adr#', 'name#', 'city#', 'adr#', 'city#', 'city#', 'ZZRE','item','item']
}
df = pd.DataFrame(data)
# Create a mask for rows where 'Type' is 'A'
mask_a = df['Type'] == 'A'
# Create a new column 'Group' to identify the groups based on occurrences of 'A' in 'Type' column
df['Group'] = mask_a.cumsum()
# Filter and remove duplicates within each group
df = df.groupby('Group').apply(lambda x: x.drop_duplicates(subset='Key', keep='last') if (x['Type'] == 'B').any() else x)
# Drop the 'Group' column as it's no longer needed
df.drop('Group', axis=1, inplace=True)
df
如您所见,Type=‘D’的重复行也被删除,这是应该保留的.不知何故,我不知道为什么过滤不起作用.