python it gives a very slow algoritm. Make changes to do it work faster. ________…
- User
python
it gives a very slow algoritm. Make changes to do it work faster.
медленный алгоритм
#%%time import pandas as pd import random
im_randomizer = pd.read_csv('im_randomizer.csv.gz')
im_randomizer['base'] = im_randomizer['base'].astype(str) im_randomizer['infm'] = im_randomizer['base'] im_randomizer ['infm'] = im_randomizer['infm'].str.replace(' ','').str.replace('}}}','}}').str.replace("'", '"').str.replace( '""', '"')
imm_all_final = pd.read_csv('2_version_tag.csv.gz', nrows=100) imm_all_final['infm'] = imm_all_final['infm']+'}' imm_all_final['infm'] = imm_all_final['infm'].str.replace(' ','').str.replace('}}}','}}').str.replace("'", '"').str.replace( '""', '"') imm_all_final
Function to randomly select a URL from DF2 for each name in DF
def merge_data(name): matching_rows = df[df['name'] == name] if not matching_rows.empty: return random.choice(matching_rows['url']) else: return name # Return the name itself if no matching rows found
def merge_data_randomizer(infm): try: matching_rows = im_randomizer[im_randomizer['infm'] == infm] if not matching_rows.empty: return random.choice(matching_rows['random']) else: return infm # Return the infm value itself if no matching rows found except KeyError: return infm # Return the infm value if 'infm' column is not found
Apply the function to each row in DF
imm_all_final['new_url'] = im_randomizer['infm'].progress_apply(merge_data_randomizer)
display(imm_all_final)
- Assistant
To improve the performance of your code, we should focus on vectorized operations instead of using apply functions with custom logic, as they often lead to slower execution times, especially on larger datasets. Here's how you can rewrite your script to be more efficient: