Posts by Paulo Marques • 3,739 points
198 posts
-
1
votes1
answer44
viewsA: Python base 64 for image
The PIL library should solve: import PIL.Image as Image image = Image.open(io.BytesIO(bytes)) Where bytes is the variable that has the bytes of the image. I hope it helps…
-
0
votes1
answer56
viewsA: How to modify a token (Spacy - Python)?
The code below works as expected import spacy from spacy.matcher import Matcher nlp = spacy.load("pt_core_news_md") doc = nlp("O João gosta da Maria.") matcher = Matcher(nlp.vocab)…
-
-2
votes2
answers100
viewsA: Search between two dates in Django
Simple: Data.objects.filter(time__range=(data_inicial, data_final)) Elegant: class Data(models.Model): dev = models.ForeignKey(Device, on_delete=models.CASCADE,related_name="data") voltage =…
-
2
votes1
answer144
viewsA: How to use objects in Django
I prefer to use the form below as it gives a visual separation. update Libraries required from django.db import models from django.utils.translation import gettext_lazy as _ end of update class…
-
1
votes1
answer93
viewsA: Python - Count the number of incidences of an event in a time window
The description below shows how to do for any group. Let’s go by parts: Preparing the base Importing libraries import pandas as pd import random Creating the Dataframe dias = 365 dti =…
-
2
votes1
answer35
viewsA: How to create this type of relationship using Django Models
I understand that a person can have one or more contacts, right? Take a look below: from django.db import models class Pessoa(models.Model): first_name = models.CharField(max_length=20) last_name =…
-
1
votes1
answer63
viewsA: Post request returns error 500
Something in the headers must be wrong. Try to leave it with as little as possible, as below, for test questions. headers = { "apikey": "<API TESTE HERE>", "Content-Type": "application/json;…
-
1
votes1
answer47
viewsA: In Python, check if the contents of one column are present in another column?
I don’t have your base so I created my own. See below: >>> import pandas as pd >>> df = pd.DataFrame({"nome": ["teste 1", "teste 2", "teste 3"], "nome_arquivo": ["um arquivo",…
-
2
votes1
answer55
viewsA: Ordering of data Pandas
I don’t know if there’s a single step to this, but with two it would be: Group by Month and Name and add Billed >>> df1 = df.groupby(["Month","Nome"])["Billed"].sum() >>> df1 Month…
-
3
votes1
answer31
viewsA: Python3 - How to stop asking for a certain number?
Changing your program a little we would have: print() print('Digite apenas números ') print() numero = int(input('Digite o número: ')) while numero != 0: if numero % 2 == 0: print(f'o número…
-
-1
votes2
answers45
viewsA: How to create independent dataframes in Python
Use conditions to assign a Dataframe to the new >>> import pandas as pd >>> df = pd.DataFrame({"PREMISSAS": range(1,100)}) >>> df PREMISSAS 0 1 1 2 2 3 3 4 4 5 .. ... 94…
-
4
votes4
answers208
viewsA: How to get an index() of an array with the same element multiple times?
I believe that the IndexOf() will not solve your problem. I’d go for something simpler 1) Position each character in a tag with a specific id <span id="0"…
javascriptanswered Paulo Marques 3,739 -
1
votes3
answers64
viewsA: optimize Camelot large pdf files
I have no way to test your program. So the answer will be more theoretical. Get to the idea: Create a list of results (dataframes) and then concatenate them See the example below: Creating the…
-
0
votes3
answers64
viewsA: Python checking if the number is Float
The best way to test is by using the method isinstance(valor, tipo) Example: valor = 13.3 if isinstance(valor, float): print("é float") else: print("não é float")…
-
1
votes2
answers116
viewsA: Optimization through dataframe (Pandas)
Based on the question below: I need to verify that the sum of the value of the items in the.txt file is equivalent to the value of the boleto in the.txt file. Use the tube gropby and sum() together…
-
1
votes2
answers77
viewsA: Split columns without Pandas tab
Two options: Use str and square brackets: df['new'] = df['col'].str[11:15] Or str.Slice: df['new'] = df['col'].str.slice(11, 15) Example >>> import pandas as pd >>> df =…
-
1
votes3
answers125
viewsA: How to add one column of data based on another in excel through Pandas?
To create a column based on another follow the steps below: Create Dataframe >>> import pandas as pd >>> df = pd.DataFrame({"compras": ["1 X 40 CONTAINERS CONTAINING 40 BAGS OF…
-
0
votes1
answer125
viewsA: Screenshot in Python
MODIFIED IN 5/Jan/2021 I believe that’s what you’re trying to do: import os import pyautogui import time foto = 'foto.jpg' pyautogui.screenshot(foto) # Desta forma o pyautogui salva a imagem if…
pythonanswered Paulo Marques 3,739 -
1
votes2
answers47
viewsA: How to remove dtype from dataframe line?
Creating a column as a result of two others is simpler than it looks Create the Dataframe import pandas as pd >>> df = pd.DataFrame({'quota_value': [10.10, 20.0, 15.50, 50.0],…
-
2
votes2
answers33
viewsA: Check whether a variable created through exec() exists
It is possible to use the locals() or globals() The locals() lists existing variables within a function. Already the globals() list the global variables. In his example: >>> number = 5…
-
2
votes2
answers51
viewsA: How do I print how many times there is a similar term in a python list?
Simply put, you could list comprehension normal = len([n for n in lista if n == 'NORMAL']) vip = len([v for v in lista if n == 'VIP']) You can also use the Counter library collections from…
-
2
votes1
answer36
viewsA: Selective and Organized Information in Python
There are some options. But, let’s go in parts. Thinking about the structure There are several players and they can be online or offline. Thinking only of this information the structure that comes…
-
2
votes1
answer234
viewsA: Remove XML file line using Python and create TXT file with result
Solution using Beautifulsoup texto = """ <catalog> <product description="Cardigan Sweater" product_image="cardigan.jpg"> <catalog_item gender="Men's">…
-
1
votes1
answer41
viewsA: Python-aligned JSON output
By your example, I understand that the JSON structure has been converted to a dictionary structure. Loop the product inside. for each in data['lojas']['todas']: for produto in each['produtos']:…
-
0
votes1
answer29
viewsA: Problems with Freqdist and Conditionalfreqdist from NLTK
To use Freqdist you have to iterate through all the words in the set. >>> from nltk.tokenize import word_tokenize >>> from nltk.probability import FreqDist >>> sent = 'Eu…
nltkanswered Paulo Marques 3,739 -
1
votes2
answers212
viewsA: Create date variable
You can create a date list and then create your dataframe Create date list >>> import datetime >>> initial_date = datetime.datetime(2020, 1, 1) >>> initial_date…
-
0
votes1
answer35
viewsA: Problem checking between two python variables
Every time you call random_bet() it can return a different value. Your while and if are "superimposed" Use as below bet = random_bet() while bet != password: print(bet) print(password)…
-
0
votes1
answer179
viewsA: Create spreadsheets with Django
I believe it would be easier to work with more than one view, using MEDIA_URL to save a temporary file. The stream would be to access the view that generates the data and this redirect to the view…
-
2
votes2
answers434
viewsA: Second highest value of a python list
A simple solution would be: Sort the list in descending order Take the second element >>> lista = [1, 3, 2, 10, 7] >>> print(sorted(lista, reverse=True)[1]) 7 However, if you have…
-
3
votes1
answer632
viewsA: Changing data from an entire table column - Python
We go to the steps using only the pandas Create Dataframe >>> import pandas as pd >>> df = pd.DataFrame({"A": ["R$ 0,921222 qualquer coisa", "R$ 1,2345 outra coisa", "R$ 0,32212…
pythonanswered Paulo Marques 3,739 -
1
votes1
answer200
viewsA: Django Error 3.1.3 Reverse for 'post_detail' not found. 'post_detail' is not a Valid view Function or Pattern name
Caro Vitor, I believe the way to solve the problem is to add the name of the app in the file urls.py, leaving him as per below: from django.urls import path, include from .views import hello_blog,…
-
1
votes2
answers128
viewsA: Put a variable inside a spin?
I believe that answers your question import spintax nome1 = input("Nome: ") nome2 = input("Nome: ") nome3 = input("Nome: ") for z in range(0,10): c = spintax.spin("{noite|dia|tarde}") n =…
-
2
votes2
answers285
viewsA: How to bring more fields in the Pandas groupby, without necessarily having to use them in the grouping?
I believe what you’re looking for is the aggregate To get the result, just: Create a desired function structure for each field f = {'contador': 'max', 'codigo': 'first'} Do the groupby with agg…
-
8
votes2
answers242
viewsA: What is virtualenv for in Python?
Python virtualenv is used to isolate the version of Python and the libraries used on a given system. If you do not use virtualenv, all the necessary libraries for your system would be installed in…
-
0
votes1
answer167
viewsA: How to transform an array of arrays into a nested array in python
Dear, I don’t know any commands that do this in a single step. In this case, I believe I have to follow the steps below: Load the numpy from numpy import array import numpy as np Define the array…
-
0
votes1
answer55
viewsA: Only json content between []
If the question is just to format the json output. The solution is to use the method dumps() library json. See below: >>> import json >>> meu_json = [ {"uf": "AL", "area":…
-
4
votes1
answer147
viewsA: Python: How to get a dictionary key based on the value?
The structure of dictionaries was created in order to quickly recover a value from a key So, see the example below: >>> tabela = {"t":148} >>> tabela["t"] 148 >>>…
-
1
votes1
answer33
viewsA: Identifying words that begin capitalized in lists
Let’s go in pieces The variable texto will take an entrance. texto = input('Texto: ') This part divides text into words using space as delimiter, however would have to assign the result to a…
python-3.xanswered Paulo Marques 3,739 -
1
votes1
answer254
viewsA: Multi-entry loop for list - Python
Normally we use the for to iterate over a list. lista = [1, 2, 3] for numero in lista: print(numero) The exit will be: 1 2 3 A tuple (as well as a list) can be accessed by the index of its element…
-
6
votes5
answers1031
viewsA: Check that all items in the list are equal
A SUPER SIMPLE SOLUTION Turn the list into a set. Should the size of the set generated be 1, so all items are equal. Example >>> l1 = [1, 2, 3, 1, 1, 2, 2] >>> print(len(set(l1))…
-
1
votes1
answer24
viewsA: My python merge PDF is not working
When pgm Python generates an error of the type below, it means that the file cannot be found, i.e., the file is not where the program thinks it is. raise IOError("%s not found." % path) OSError:…
pythonanswered Paulo Marques 3,739 -
0
votes1
answer135
viewsA: Read certain columns of xls file in Python with XLRD
Opa, I believe you’re looking for the method col_values. See the documentation. col_values(colx, start_rowx=0, end_rowx=None) Returns a Slice of the values of the Cells in the Given column. In your…
-
3
votes2
answers54
viewsA: How to interrupt the algorithm?
Expensive, Identation in Python is crucial. His last if forehead media_rec will be executed regardless of whether the student has passed or not and this variable is only initialized if the student…
pythonanswered Paulo Marques 3,739 -
1
votes1
answer79
viewsA: Run event on Tkinter button
Rodrigo follows below a small example: from tkinter import * root = Tk() def muda_title(nome=""): root.title(f'Hello {nome}') muda_title("Tkinter") button = Button(master=root, text='Muda o titulo',…
-
0
votes1
answer76
viewsA: How do I create a Slug automatically from the title of an item created with a Django form
If it is while the person type, you will have to use javascript or similar and then it is better to post in another forum. If it is after the person submits (createTeam) just put between the lines…
-
0
votes3
answers71
viewsA: Algebraic System - Python
Expensive, Although the solution below has no test, see if it helps you in solving the problem. I commented on the code because I thought it would be better to do a paragraph describing what it…
-
0
votes1
answer351
viewsA: pass the value of a python variable to a mysql search
Treat your SQL command like you did on print of your first block of code. For any Python version you can pass the parameter in the sql string as below comando_sql2 = 'select data_ordenha from leite…
-
1
votes2
answers95
viewsA: HTML alignment using Python
You can use the Beautiful Soup from bs4 import BeautifulSoup as bs content = '<li><a href="dsadas">dsadaads</a></li><li><a…
-
1
votes2
answers97
viewsA: How to access a list that is inside another list in Python?
There are better ways to store your data as a list of dictionaries, or namedtuple lists. If the student model were more complex, it would still have the list of classes defined by the programmer.…
-
0
votes1
answer81
viewsA: How to get the value of a Variable associated with a Checkbutton in Tkinter? - Python
I don’t know anything like that "var get.()", but you can take the builtin __dict__ and take the contents of the key _tclCommands. For this example works. from tkinter import * root = Tk() def…