我正在尝试根据列item_id从dataframe df中删除重复项。
df:
date code item_id
0 20210325 30893 001 002 003 003
1 20210325 10030 001 002 003 003 在这个df中,item_id如下所示:
These are all item_ids separated by one or more spaces.
0 -> "001 002 003 003" #here there is an extra space after 001, rest is same.
1 -> "001 002 003 003"我使用以下函数移除重复项。
def create_data_file_removed_duplicate_item(packing_data):
print('start removing duplicated item data')
print('data count before removing duplication: ' + str(len(packing_data)))
# check null
packing_data = packing_data[~packing_data['item_id'].isnull()]
# sorting item id
packing_data['item_id_list'] = packing_data['item_id'].str.split(' ').apply(sorted)\
.apply(lambda item_id_list: ''.join([item_id.replace(' ', '') + ' ' for item_id in item_id_list]))
# drop duplicate item_id
packing_data.drop_duplicates(keep='last', inplace=True, subset=['item_id_list'])
packing_data = packing_data.drop(columns=['item_id_list'])
# create non duplicate item data file
print('data count after removing duplication: ' + str(len(packing_data)))
return packing_data虽然有类似的0和1行,但我无法删除重复的item_id。
在其他一些情况下,此函数移除重复的item_id,如下所示:
0 -> "001 002 003 003". # there is no space after 001. These are all item_ids separated by one or more spaces.
1 -> "001 002 003 003"Expected output
date code item_id
0 20210325 10030 001 002 003 003 即使item_id被多个空格隔开,我是否也可以删除副本呢?
发布于 2021-06-15 14:29:02
您可以将一个函数应用到将使item_id“统一”的列,然后drop_duplicates()
import pandas as pd
df = pd.DataFrame({'date':['20210325','20210325'],
'code':['30893','10030'],
'item_id':['001 002 003 003','001 002 003 003']})
df['item_id'] = df['item_id'].apply(lambda x: ' '.join(sorted(x.split())).strip())
df = df.drop_duplicates(subset='item_id', keep="last")输出:
print(df)
date code item_id
1 20210325 10030 001 002 003 003发布于 2021-06-15 14:29:05
创建一个移除空格的临时列,然后根据该列删除重复项。
import pandas as pd
df = pd.DataFrame({'date': [20210325, 20210325],
'code': [30893, 10030],
'item_id': ['001 002 003 003', '001 002 003 003']})
df = (df.assign(t=df['item_id'].str.replace(' ', ''))
.drop_duplicates('t').drop(columns='t'))
print(df)
# date code item_id
#0 20210325 30893 001 002 003 003https://stackoverflow.com/questions/67988115
复制相似问题