Converting for loop to extract values from a data frame using various lists

In the scenario where I have two lists, list1 and list2, along with a single data frame called df1, I am applying filters to append certain from_account values to an empty list p.

Some sample values of list1 are: [128195, 101643, 143865, 59455, 108778, 66042, 138456, 66043]

And here are a few values from list2: [128594, 128599, 128596, 128588, 128168, 125410, 127166, 127078]

p=[]
for i in list1:
    for j in list2:
        ss=df1[df1.to_account==i]
        for k in range(0,len(ss.from_account)):
            if(ss.from_account.values[k]==j):
                p.append(j)

Currently, the execution time using a for loop is quite lengthy. Are there any alternative methods that can produce the same result but more efficiently in terms of execution time?

Answer №1

It appears that the variable ss.from_account.values represents a list, so instead of iterating through it using variable k, you can simply verify if the value exists within that list:

result=[]
for item in items_list:
    ss=df1[df1.to_account==item]
    for value in values_list:
        if value in ss.from_account.values:
            result.append(value)

In addition, I have adjusted the position of the declaration of ss outside the inner loop, eliminating unnecessary repetitions. There is potential for further optimization with the following revised code:

results=[]
for item in items_list:
    ss=df1[df1.to_account==item]
    results += [value for value in values_list if value in ss.from_account.values]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a Python serverless function on Vercel using Next.js is a streamlined

Discovering the capability of using Python to create a serverless function within a Next.js project was truly exciting. Once deployed on Vercel, it seamlessly transforms into a serverless function. Browsing through the documentation, I stumbled upon a str ...

Changeable text. / Programming with Python / Kivy framework

My program consists of 2 buttons that, when pressed, display in the IDE terminal which button was pressed and how many times. However, I am currently struggling to display the counting number in a label above each button. I have attempted several solutions ...

What's causing the no attribute error in Selenium with Python?

This is the error that is displayed in my console: An AttributeError: 'WebDriver' object does not have the attribute 'find_element_by_link_text' Upon examining the source code of the website I am working on, I found that the link I ne ...

Is there a way to automate saving the initial search result link from Google using Selenium?

My current project involves searching for the government websites of various city names and states. I've developed a code that utilizes the "I'm feeling lucky" search option to automatically open the first search result and add the URL to a list. ...

Unresolved issue with Flask failing to retrieve URL argument from AJAX request

I'm having trouble with retrieving a submitted string from the server using Flask's Request module. The URL arguments don't seem to be picked up correctly, resulting in receiving "HELLO" instead of the actual string variable. Additionally, ...

Troubleshooting Routing Problems in Python with Flask

My function has several possible routes: @bp.route('/list/', defaults={'status': None, 'time': None, 'search': None}) @bp.route('/list/lot/', defaults={'status': None, 'search': None, &a ...

Which is more suited to use in this Python function: a global variable or a parameter?

I am seeking clarification on the code provided below, which may also be relevant to other functions. This particular function is designed to calculate the maximum path and its length for a Directed Acyclic Graph (DAG), based on the input of the Graph, sou ...

Using Kivy's TabbedPanel: How can you invoke the switch_to function from a different class?

In the code snippet below, I am trying to make the button on the edit_button_tab switch to the edit_input_tab. This is crucial for me as I need to toggle between predefined classes EditButton and EditInput within a larger program. The layout contains sever ...

Is there a way to verify if the viewed file is in .xlsx or .csv format?

Currently utilizing the openpyxl module, however it has come to light that it does not support csv format. Therefore, I am currently seeking a solution on how to distinguish whether the incoming file is in .xlsx or .csv format. ...

Python Selenium: Guide to choosing an option from a SELECT element

As a newcomer to Python, I am curious about how to extract my option from a SELECT element. Specifically, I am interested in selecting the first option within the SELECT tag. I have attempted various methods without success. The current error message I en ...

What is the best way to replicate a string in python?

Is there a way to repeat a string in Python without having to write it out multiple times? For instance, instead of manually typing out print ('---------------------------'), is there a more efficient way to achieve the same result by repeating ...

Facing Challenges with Python Selenium while Accessing Specific Form Elements in Salesforce

Recently, I've been using Selenium to automate some data entry tasks on Salesforce. So far, my script successfully loads the webpage, allows me to log in, and clicks an "edit" button. Now, I'm encountering an issue when trying to input data into ...

Difficulty locating the element

Recently, I delved into the world of coding and decided to create a form filler for Nike.com using the Selenium Chrome webdriver. However, I encountered a stubborn pop-up related to cookies that is preventing me from successfully filling out the form. You ...

Is there a way to attach an audio file to a video clip using moviepy without having to re-encode the

I've been experimenting with the following code: from moviepy.editor import * videoclip = VideoFileClip("filename.mp4") audioclip = AudioFileClip("audioname.mp3") new_audioclip = CompositeAudioClip([audioclip]) videoclip.audio = n ...

Is there a way to include both an extension and its settings in the chrome driver's extensions?

Currently, I am using Python, Selenium, and Chromedriver to develop a program that automatically fills out forms. However, I am interested in integrating a specific Chrome extension called "Autofill" which features a lightning bolt icon. This extension a ...

Pressing on item in the command prompt

It's interesting to see that hyperlinks in my Debian/Linux terminal can be clicked and open the browser. I'm curious if this functionality could be extended for other purposes beyond just hyperlinks, or if it's specifically designed only fo ...

I am having difficulty locating or clicking on an element on my page using Selenium, Python, findelement, and Xpath methods

I am facing difficulty in locating an element on a webpage after logging in successfully to the website. My goal is to click on a button that appears only after midnight to participate in an activity. However, I do not want to stay glued to my PC just to ...

Selenium-powered Python Web Scraping

I am attempting to gather product information from Amazon, but I keep encountering the error NoElementException: Message: unable to find element: {"method":"xpath","selector":"//li[@class='a-last']"} (Session info: chrome=102.0.5005.115) The cod ...

Press on Selenium with Python

I am experiencing an issue with clicking in Selenium as it is not able to click on the button. Below is the code I am using: from selenium import webdriver import time import click from selenium.webdriver.support.select import Select from selenium.webdriv ...

Encountering difficulties with resolving captcha through a specific service

Utilizing a somewhat hardcoded approach, I extract the site-key with confidence due to its consistent length. Following that, I make use of the 2captcha API Documentation to send a POST request for the captcha token retrieval. However, I encounter two sign ...