【发布时间】:2021-07-14 06:45:27
【问题描述】:
我正在努力制作一个更快的代码来将相似的产品名称(列“prep”)分组到相同的“person_id”和相同的“TNVED”中。所以我的数据框示例如下所示: sample_of_dataframe
所以我在 IIN_BIN 上做了字典,这本字典的键是 TNVED。键的值也是字典,键为group_ids,用fuzzywuzzy按相似度分组。
from fuzzywuzzy import fuzz
import warnings
warnings.filterwarnings("ignore")
length = len(np.unique(df['IIN_BIN'].to_list()))
t1 = time.time()
amount = 0
dict_main = {}
df['prep']=df['prep'].fillna("")
for BIN in np.unique(df['IIN_BIN'].to_list()):
temp_list_BIN = df[df['IIN_BIN'] == BIN]['TNVED']
dict_pre_main = {}
for tnved in np.unique(temp_list_BIN):
dict_temp = {}
j = 0
df_1_slice = df[df['IIN_BIN'] == BIN]
df_1_slice = df_1_slice[df['TNVED'] == tnved]
df_1_slice.reset_index(inplace = True)
df_1_slice.drop(['index'], axis = 1, inplace = True)
while len(df_1_slice) != 0:
temp_list = []
temp_del_list = []
temp_fuzz_list = []
temp_df = pd.DataFrame(columns = df_1_slice.columns)
for i in range(0, len(df_1_slice)):
fuz_rate = fuzz.token_sort_ratio(
df_1_slice['prep'][0], df_1_slice['prep'][i])
if fuz_rate >=90:
temp_del_list.append(i)
temp_list.append([0,i,fuz_rate])
temp_fuzz_list.append(fuz_rate)
temp_df = temp_df.append(df_1_slice.loc[i])
dict_temp[j] = temp_df
df_1_slice.drop(temp_del_list, axis = 0, inplace = True)
df_1_slice.reset_index(inplace = True)
df_1_slice.drop('index', axis = 1, inplace = True)
j+=1
dict_pre_main[tnved] = dict_temp
dict_main[BIN] = dict_pre_main
time_gone = time.time() - t1
if amount%60 == 0:
print('Percentage of BINs proceeded: ', amount/length,
'%. Time gone from start: ', time_gone, ' s.')
amount+=1
可能有一种更快的方法可以做到这一点,因为我必须将所有这些字典解压缩到一个数据帧中,这需要我大约 1-2 天才能获得 200 万行数据帧?
t1 = time.time()
temp_list = list(df.columns)
temp_list.append('group_sorted')
concat_full = pd.DataFrame(columns = temp_list)
length = len(dict_main.keys())
amount = 0
for key_iin in dict_main.keys():
for key_tnved in dict_main[key_iin].keys():
for key_group_number in dict_main[key_iin][key_tnved].keys():
dict_main[key_iin][key_tnved][key_group_number]['group_sorted'] = key_group_number
concat_full = concat_full.append(
dict_main[key_iin][key_tnved][key_group_number])
time_gone = time.time() - t1
if amount%60 == 0:
print('Percentage of BINs proceeded: ', amount/length,
'%. Time gone from start: ', time_gone, ' s.')
amount+=1
concat_full.to_csv('item_desc_fuzzied.csv', index = False)
可能有更快的方法吗?
【问题讨论】:
标签: python pandas loops dictionary fuzzywuzzy