Posts by Paulo Marques • 3,739 points
198 posts
-
2
votes1
answer50
viewsA: Compile error using Selenium: Binary is not a Firefox Executable
Firefoxbinary has to point to Firefox binary (executable), not geckodriver binary. The configuration below should work: from selenium import webdriver from selenium.webdriver.firefox.options import…
-
0
votes1
answer20
viewsA: create array through a python file
Some questions with your code. arquivo = open('arquivo.txt', 'r') # 1 linha = {} # 2 linha = arquivo.readline() # 3 print(linha[0]) # 4 Note #1 This line is OK Note #2 This line has no reason to be…
pythonanswered Paulo Marques 3,739 -
1
votes1
answer24
viewsA: Value_counts - Pandas - Dataframe - Zero Quantity
Based on the above comment: Importing libraries import pandas as pd import random Auxiliary variables tamanho = 1000 horas = [0,1,2,3,4,5,6,7,8,9,10,13,14,15,16,17,18,19,20,21,22,23] # sem 11 e 12…
-
0
votes1
answer14
viewsA: pivot_table of frequency
I believe that groupby with the agg is the solution. See the example: Loading libraries import pandas as pd import random Auxiliary variables sexos = ["M", "F"] ufs = ["BA", "ES", "MT", "RJ", "SP"]…
-
-3
votes1
answer50
viewsA: Equal names different file extensions
There are several ways to do it, follow one of them: import os path = 'COLOQUE_AQUI_O_PATH_PARA_DIRETORIO_COM_ARQUIVOS' txt_files = [f for f in os.listdir(path) if f.endswith('txt') and…
python-3.xanswered Paulo Marques 3,739 -
1
votes1
answer31
viewsA: Is it possible to replace certain values with NA in pandas without the use of loops?
We have two scenarios: Columns that have integers that should be string Columns that have string that should be integer For the first case, for example, the whole case 1 has to become the string 1,…
-
0
votes1
answer50
viewsA: Extract text from a python string
If the codes have a training standard as per your example LL-NNN.NNN, where L corresponds to a letter uppercase and N corresponds to a number. In addition, both the hyphenate as to the dot appear at…
-
1
votes1
answer24
viewsA: Sort data in dataframe pandas by repeating frequency of each element
In detail: Loading library import pandas as pd Creating Dataframe for Testing df = pd.DataFrame({"A": [1,2,3,1,2,3,1,1,2,2,1,3]}) print(df) A 0 1 1 2 2 3 3 1 4 2 5 3 6 1 7 1 8 2 9 2 10 1 11 3…
-
0
votes2
answers41
viewsA: How to map values with Dataframe pandas
From what was presented, it seems that the Dataframe is not huge. So, the solution below would meet Loading libraries import pandas as pd import numpy as np Creating Test Dataframe df1 =…
-
0
votes2
answers34
viewsA: How to access an attribute or method from a variable?
You can use the eval to do what you want. def desc(): lista_colunas = ['Pclass', 'Age', 'Parch', 'Fare'] lista_medidas = ['mean','max','min','std','var'] for medida in lista_medidas: for feat in…
-
0
votes1
answer14
viewsA: Modulenotfound when I try to import an external library
If the library is for image manipulation the correct is: Installation pip install Pillow Note Pillow with the letter P capitalized. Carrying import PIL or from PIL import Image…
-
0
votes2
answers54
viewsA: Can someone help me subtract one list from another?
The operations you want are set operations. python has its own data structure called set() See below: >>> lista_inicio = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K", "A"]…
-
1
votes1
answer37
viewsA: I would like to know faster ways to execute the insertion of information in one column based on the value of another
Whereas the product fields are empty, i.e., empty string (""). Follow the steps below: Creating Dataframe for Testing import pandas as pd df = pd.DataFrame({"id_relato": [456, 456, 456, 789, 789],…
-
2
votes1
answer36
viewsA: Python: consolidate duplicate lines by adding values
Use the groupby and then the to_excel as below import pandas as pd planilha = pd.read_excel(r"C:\Users\wjrs1\Downloads\nova.xlsx", engine='openpyxl') novo_df = planilha.groupby(['Matrícula',…
-
3
votes2
answers60
viewsA: Doubt in python with Opencv
The reason you didn’t succeed is because of the original image (img_src) be a numpy array where each element has three values, but the image Canny (canny) is a numpy array where each element has the…
-
1
votes3
answers34
viewsA: Doubt about converting str to int with py/pandas ((dataset))
In average, median and fashion calculation; the value NaN is ignored. Give preference to the type float. Take the example: Creating Dataframe Test df = pd.DataFrame({"valores": ["1", "1", "Unknown",…
-
4
votes1
answer61
viewsA: Add values from a column that are duplicated using groupby as python criteria
I believe you have to use the reset_index Take the example: Creating Dataframe import pandas as pd df = pd.DataFrame({"A": [1,2,1,3,4], "B": [1,2,1,3,4]}) df Out[3]: A B 0 1 1 1 2 2 2 1 1 3 3 3 4 4…
-
6
votes2
answers100
viewsA: Sort two lists simultaneously, by notes in ascending order, then by name
Further pythonic, could be: Creating variables notas = [5, 7, 9, 3] nomes = ["Alfredo", "Camila", "Debora", "Joao"] Gathering lists l = list(zip(nomes, notas)) print(l) [('Alfredo', 5), ('Camila',…
-
2
votes1
answer15
viewsA: Error in get_absolute_url Django
In the function below, you are passing as parameter the self.id def get_absolute_url(self): return reverse('main:list_produtos', args = [self.id]) The url is not ready to receive parameters:…
-
0
votes2
answers53
viewsA: How to check if a variable received a new python value?
In a generic way do something like: class ConexaoBanco(): _instance = None def __init__(self): pass @staticmethod def get_instance(): if ConexaoBanco._instance == None: ConexaoBanco._instance =…
-
1
votes2
answers73
viewsA: I can’t understand my mistake with FOR and Dataframe
The most performative solution would be: BRICS["Densidade"] = BRICS['População'] / BRICS['Area'] Use for, apply, assign with the aid of a function (named or lambda) is slower. For more details see…
-
-1
votes1
answer37
viewsA: Delete method does not work
You have in your file urls.py two urls pointing to different methods. It will always fall on the first if you pass books/<int:pk>/. I believe that the best would be to do something like below:…
-
4
votes3
answers74
viewsA: Picking numbers from a string - python
Simply put, you can do it: txt = '<SCANNER A7899739503929>' somente_digitos = ''.join([d for d in txt if d.isdigit()]) print(somente_digitos) '7899739503929' If you have a list >>>…
-
0
votes1
answer25
viewsA: How to remove duplicate names in rows from a python dataframe?
I see here two distinct cases: Case 1: All value of Nomes which has the delimiter vírgula (,) is obligatorily repeated Case 2: The values of Nomes that having a comma is not necessarily a repeated…
-
1
votes1
answer31
viewsA: Pandas - Exhibition after groupby
The reset_index() is your friend in this case. See the example below: Creating Test Dataframe >>> import pandas as pd >>> df = pd.DataFrame({"Escritorios": ["A", "A","A","A","A"],…
-
0
votes2
answers50
viewsA: Python - Doubt-transform into Dataframe
The library pandas has a specific method to create a dataframe from a query SQL. The method is the read_sql_query df = pandas.read_sql_query("SELECT ROTAID,DESCRICAO FROM ROTAS", con=cursor) The…
-
2
votes1
answer53
viewsA: How to replace a column conditionally in Pandas?
Accuse NAY do for in a dataframe. This would be the last resort as it is not performative at all. See this link To replace all those equal to 53 by 1, do: df.loc[df['semana'] == 53, 'semana'] = 1…
-
0
votes2
answers41
viewsA: Compare lines Dataframa Pandas
Another way of doing Loading library and creating test dataframe import pandas as pd df = pd.DataFrame({"cpf": [1,2,3,2,3,3,4,1,1,4], "data":["01/01/2021", "01/02/2021", "01/03/2021", "01/06/2021",…
pandasanswered Paulo Marques 3,739 -
2
votes1
answer32
viewsA: rename rows of a dataframe
Use groupby() with cumcount() Creating Dataframe df = pd.DataFrame({"codcliente": [7,7,7,2,2,3,3,3,3,3],"contrato": [1180000007004, 1180000007003, 1090000007038, 1090000007035, 1090000007029,…
-
0
votes1
answer36
viewsA: How to use groupBy with pd. Cut?
I believe the solution may be using the method between Creating Dataframe df = pd.DataFrame({"jul": [34252, 33850, 34850, 35850, 36850, 37850, 38850, 39850, 40850, 41850, 42850], "ago": [52000,…
-
0
votes1
answer32
viewsA: Problems with print in python socket
If you guarantee that the message is less than 1024, this will serve Server #SERVIDOR from socket import * from time import * sala = socket(AF_INET, SOCK_STREAM) sala.bind(('', 58117)) sala.listen()…
-
4
votes1
answer57
viewsA: Doubt For i Range Python
When we use pandas or other libraries, we have the idea that they solve everything. Python has numerous libraries that, working together, make it a super programming language. That said, let’s get…
-
0
votes2
answers67
viewsA: Problem when declaring 2 variables
Changing only a little import sys def soma (num1, num2): return num1 + num2 try: s1, s2 = input("Insira 2 valores separados por vírgula: ").split(",") except: print("Erro na entrada de dados.")…
-
0
votes2
answers68
viewsA: Join cells with python
Oops, I believe whatever’s going on is that the item in your script is receiving the split(' '). So the result for: Petrobras PN 23,67 23,81 23,47 +0,05 +0,21% 15,74M would be: ['', '', '', '',…
-
1
votes1
answer73
viewsA: How can I check if a column of a dataframe is contained in a column of another dataframe?
Assuming that it is coluna2 has to be inside the coluna, I believe the best way is to use set.issubset(). Creating Test Dataframes >>> df1 = pd.DataFrame({"coluna": [ '1', '2', '3', '4',…
-
3
votes1
answer133
viewsQ: How to test the application with Kivymd?
I’ve developed a small test app that checks both the battery status and whether the phone is being charged. The app is running local from python main.py, but when I install it in Android Studio…
-
1
votes1
answer54
viewsA: Syntax Error (Phyton)
Even if the suggestion in the comments worked, it is not performative in large dataframes because of the use of apply(), that although it’s faster than a for index, row in df.iterrows(); is slower…
-
0
votes1
answer31
viewsA: How to compare if the value of a dataframe column is in an array if you are creating a new column with that value?
If I understand correctly, use the isin() Creating list and dataframe for testing >>> lista = array(['NF', 'BT', 'C', 'N', 'I', 'IP', ... 'Aa', 'Sa', 'Gl', 'Et', 'To', 'Hr', ... 'Cr', 'Ro',…
-
0
votes3
answers84
viewsA: Dataframe Pandas - How to use a previous value other than NA for calculation
NOTE: The solution presented below NAY will meet if existing numbers are repeated. Defining dataframe >>> df = pd.DataFrame([['A',1,100],['B',2,None],['C',3,None],['D',4,182],['E',5,None]],…
-
1
votes1
answer30
viewsA: How to make classes with multi-level functions?
I’m not reproducing everything that’s in your example, but I think you can get an idea. Defining Beta >>> class Beta: ... def __init__(self, a, b): ... self.a = a ... self.b = b ... def…
-
0
votes1
answer22
viewsA: Using Loginrequiredmixin with Login Formview
To make the view be used only if the user is logged in, see below: Configure in Settings LOGIN_REDIRECT_URL = 'login_page/' LOGOUT_REDIRECT_URL = '/' Decorate the view from…
-
0
votes1
answer53
viewsA: Print of the smallest number of a pandas table
Using the data posted in the comment. Importing library >>> import pandas as pd Uploading file >>> contas = pd.read_csv('dados.csv', delimiter=";") Filtering dataframe >>>…
-
2
votes1
answer126
viewsA: How to replace a comma for an integer df point without having to do column for column - Python
just apply the rule to every dataframe Creating Dataframe Test >>> import pandas as pd >>> df = pd.DataFrame({"A": ["Teste com, virgula", "Outro, teste"], "B": ["Nada aqui", "Mas,…
pythonanswered Paulo Marques 3,739 -
2
votes1
answer130
viewsA: How to store print values in a variable in Python?
One way is to use the loc Example: Creating Test Dataframe >>> df = pd.DataFrame({"idade": [18, 22, 19, 21], "nome": ["Joao", "Pedro", "Sergio", "Murilo"]}) >>> print(df) idade…
-
1
votes1
answer65
viewsA: Classification of grammar in nltk
See the example below: import nltk from nltk.stem.snowball import SnowballStemmer def stemming_bag(words, stemmer): return [stemmer.stem(w) for w in WORDS] def imprime(w, result): return list(zip(w,…
-
0
votes2
answers28
viewsA: How to do procedure in Pyhton Jupyter lab with a number list and not just with a list item
I believe that the list comprehension will not help you in this, because of if. Use a normal structure of for theta_list = [] for x,y in zip(media_v1, media_v2): theta = 180 * math.atan(y/x)/math.pi…
pythonanswered Paulo Marques 3,739 -
-1
votes1
answer94
viewsA: How to import CSV files from a same level folder (and/or above) in Python?
In the main.py do something like: import os diretorio_base = os.path.dirname(os.path.abspath(__file__)) # ou use "." no lugar do `__file__` diretorio_data = os.path.join(diretorio_base, "data") When…
-
0
votes1
answer51
viewsA: Incorrect value of Agg Mean
The script is doing what it should. Assuming the averages are wrong at 0.5 is wrong. Some points: range(0,120) will create a list starting at zero and ending at 119. pd.cut will create 6 ranges…
-
1
votes1
answer44
viewsA: By importing a given CSV into the notebook jupyter and turning a variable to 0 and 1 hour to show the table again this as Nan
Though I see it’s been solved. When we have a categorical variable, depending on the case, the use of "Category" is ideal. Creating Test Dataframe >>> df = pd.DataFrame({"Sex":…
pythonanswered Paulo Marques 3,739 -
0
votes1
answer30
viewsA: In a df, how to select items in column with datetime format, classify them into periods (morning, afternoon and evening) and place them in a new column
Follow the steps below Creating Test Dataframe >>> import pandas as pd >>> df = pd.DataFrame({"DataString": ["29/01/2019 17:50:11", "29/01/2020 3:50:00", "29/01/2021 21:50:11"]})…