Set a pandas-filtered value as a variable in Python

Having an issue with using pandas to filter data from a column in my worksheet and assign values to variables.

The code snippet below shows my attempt at filtering:

variable = clientes.loc[(clientes['Data']=='08/02/2023')]
print(variable)

Here is the result of the filter:

 Nome do paciente        Data Horário  Email     Telefone Tipo de agendamento           Situação Status Financeiro Observação
34          Teste 1  08/02/2023   10h00    NaN          NaN                 NaN  Paciente agendado          Não pago        NaN
35          Teste 2  08/02/2023   13h30    NaN          NaN                 NaN  Paciente agendado          Não pago        NaN
36          Teste 3  08/02/2023   15h00    NaN   55544454.0    Consulta Simples  Paciente agendado          Não pago        NaN
37          Teste 4  08/02/2023   18h00    NaN  555445454.0    Consulta Simples  Paciente agendado          Não pago        NaN
38          Teste 5  08/02/2023   20h00    NaN          NaN                 NaN  Paciente agendado          Não pago        NaN

Now, I need to store these values into a variable, preferably as a list:

   Nome do paciente      Data      Horário
    Teste 1            08/02/2023   10h00
    Teste 2            08/02/2024   13h30
    Teste 3            08/02/2025   15h00
    Teste 4            08/02/2026   18h00
    Teste 5            08/02/2027   20h00

I've looked at a solution on Stack Overflow but couldn't adapt it to my code:

Pandas assigning value to variable with two column filters from dataframe

Answer №1

In order to get the desired result, make sure to specify the columns you need in the code snippet provided below.

selected_data = patients.loc[(patients['Date']=='08/02/2023')][['Patient Name', 'Date', 'Time']]

print(selected_data)

result_list = []

[result_list.extend(item) for item in selected_data.values.tolist()]

print(result_list)

The output of result_list will be similar to the following list:

['Test 1', '08/02/2023', '10:00 AM', 'Test 2', '08/02/2024', '01:30 PM'...................]

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

It is impossible to load JSON into a variable

I have been using this amazing module called scholarly.py for my research work. If you want to check it out, here is the link: https://pypi.org/project/scholarly/ This module functions flawlessly, but I am facing an issue where I cannot store the output ...

Spider login page

My attempt to automate a log in form using Scrapy's formrequest method is running into some issues. The website I am working with does not have a simple HTML form "fieldset" containing separate "divs" for the username and password fields. I need to id ...

Minimizing data entries in a Pandas DataFrame based on index

When working with multiple datafiles, I use the following code to load them: df = pd.concat((pd.read_csv(f[:-4]+'.txt', delimiter='\s+', header=8) for f in files)) The resulting DataFrame looks like this: ...

What is the best method to generate a new table in pandas that is built from an existing table?

After reading this post on reordering indexed rows in a Pandas data frame based on a list, I tried the following code: import pandas as pd df = pd.DataFrame({'name' : ['A', 'Z','C'], 'company ...

Converting HTML table to pandas dataframe: Extracting data from HTML elements

After extracting data from a large table on the web using requests and BeautifulSoup, I encountered an issue with specific parts of the information. Here is a snippet of the table: <table> <tbody> <tr> <td>265</td> <td> ...

"Problem with rendering languages in right-to-left direction on Plotly charts when using fig.write_image to save as a JPG

I am experiencing an issue when trying to export a chart to jpg in languages that are right-to-left direction, such as Arabic, Hebrew, and Urdu. When using the command "plotly.offline.plot" to export to .html, there is no problem and all brackets display c ...

Google AppEngine Endpoints encountered an error: Unable to retrieve service configuration (HTTP status code 404)

I am currently following the instructions outlined in the Quickstart guide. While working on this, I came across another query related to the same topic. I made sure that the env_variables section in my app.yaml file contains the correct values for ENDPO ...

I am encountering a TypeError because the type being used is unhashable, specifically a 'list'. How do I go about inserting an image into a list while preserving

Within my views.py file, I have the following code: import os import cv2 from pathlib import Path path1 = Path(__file__).parent / "../test1" path2 = Path(__file__).parent / "../test2" index_list = [] for i in path1.iterdir(): i = str(i) if i.split(" ...

I need assistance with adding an icon to a qinputdialog in my pyqt4 application. Can someone provide

Below is the code snippet I am currently working with: languages = ['English', 'rus', 'uk', 'fr', 'germ'] s, ok = QtGui.QInputDialog.getItem(window, 'title', 'help', languages, curre ...

Python Web Scraping: Issues with Duplication and Displaying Outputs

I have encountered a problem in my code that is causing issues with the output of loops and inserting data into my database. Despite attempting to troubleshoot, I am unable to pinpoint the exact source of the problem. What I am striving for is to have each ...

How can you transform a string into a dataframe using Python?

I am extracting and printing strings from telnet using the following code snippet. output = tn.read_until(b"[SW]").decode('ascii') print(output) The variable type of output is string. It displays information in the following format: Total AP i ...

Selenium is unable to locate an element using Jquery

sel.add_script( sel.get_location(), "jquery.js") #I am getting u'fd6c42bcc770ca9decc4f358df3688290a4257ad' idOfResultWithSomeImage=sel.get_eval("window.jQuery('#result').find('img').filter('[alt=SeleImage]') ...

Utilizing Runge-Kutta fourth order method for solving a system of Ordinary Differential Equations (ODEs

In an attempt to solve a 2x2 system of First Order Differential Equations with given initial conditions using Python, here is the code I have written: from math import * import numpy as np np.set_printoptions(precision=6) ## controlling numpy output deci ...

Assistance Needed with Python XPath

Newbie to Python/Selenium. Seeking assistance in locating code 1203 within the third div, and then identifying the corresponding input checkbox. Currently struggling with the code provided below. Your support would be greatly appreciated. driver.find_ele ...

Searching for a specific record in a SQLite database using a tkinter entry box in Python and retrieving the result

My latest project involves creating a library program that uses a database to store information about books, complete with tkinter for the graphical user interface. One highlight is a feature where users can input a book's name in order to search the ...

Creating a single image by merging RGB colors from multiple images using Python and Cimpl

In order to create a unique image, the challenge is to combine three RGB pictures into one original picture. The process involves taking three filtered images in RGB format of the same picture - one red, one green, and one blue. A method attempted was to e ...

When utilizing Beautiful Soup and Scrapy, I encountered an error indicating a reference issue prior to assignment

I encountered an issue while trying to scrape data which resulted in the error message UnboundLocalError: local variable 'd3' referenced before assignment . Can anyone provide a solution to resolve this error? I have searched extensively for a so ...

Utilizing Selenium WebDriver in Python to locate and interact with WebElements

Currently, I am utilizing Selenium for real-time web scraping. However, I am encountering issues searching for a specific WebElement even though the documentation indicates that it is feasible. while True: try: member = self.pdriver.find_all(" ...

Ways to eliminate attributes from dataclasses

I am working with a dataclass that looks like this: @dataclass class Bla: arg1: Optional[int] = None arg2: Optional[str] = None arg3: Optional[Dict[str, str]] = None My objective is to achieve the following behavior: >>> bla = Bla(a ...

Can one predict the number of iterations in an iterator object in Python?

In the past, when I wanted to determine how many iterations are in an iterator (for example, the number of protein sequences in a file), I used the following code: count = 0 for stuff in iterator: count += 1 print count Now, I need to split the itera ...