Posts by Paulo Marques • 3,739 points
198 posts
-
1
votes1
answer171
viewsA: Python - consume loop api for paging
Using requests would be something like: import requests page = 1 while True: # supondo que a chamada passe a página como parâmetro r = requests.get(f'https://dominio?page={page}') # testando…
pythonanswered Paulo Marques 3,739 -
0
votes1
answer32
viewsA: Calculating difference between first and last line in a dataframe pandas
If you don’t have Nan as the first or last element, follow the Low steps Creating dataframe df0 = pd.DataFrame({'Temp01':[10,20,30,40,15],'Temp02':[50,60,70,70,45],'Temp03':[80,90,100,100,75]})…
-
1
votes2
answers45
viewsA: Value Replace with Python and Pandas
Having the dataframe below: >>> df txt 0 [23/Mar/2021:00:00:00 1 [23/Mar/2021:00:00:00 2 [23/Mar/2021:00:00:00 3 [23/Mar/2021:00:00:00 Just do df['txt'] = df['txt'].str.replace('\[', '')…
-
1
votes1
answer77
viewsA: Remove row and column numbering from the Dataframe of an Array
The horizontal numbers are showing up because you used header=None Change to df_cronograma=pd.read_csv('cronograma.csv', sep=';') df_custohora=pd.read_csv('custohora.csv', sep=';') The vertical…
-
1
votes2
answers72
viewsA: Logic (if,Elif,Else) with python error
A brief explanation A very common error is to use lambda calling a function and in this function reference the whole dataframe, when the ideal would only be to reference the line Example: For the…
pythonanswered Paulo Marques 3,739 -
0
votes1
answer54
viewsA: My dataframe skips a line in excel when Columns receives more than one line (pandas)
Did you find or knot that needs to be untied by the people of pandas. It is a matter of their choice. Although it is not a bug, the result is as if it were. This is only perceived when the column…
-
0
votes1
answer17
viewsA: ROOT-Cern import inside a virtual env and inside lxplus
In the documentation for the installation of Pyroot, NAY it is stated that it can be installed via `Pip install For installation in the Conda, according to the same documentation, do: $ conda create…
-
0
votes1
answer48
viewsA: Host issues when connecting two computers with socket-py
Your client is pointing to localhost while your server is picking up the machine name with socket.gethostname() On the server use: HOST = "localhost" or HOST = "127.0.0.1" or HOST = "0.0.0.0" The…
pythonanswered Paulo Marques 3,739 -
4
votes1
answer53
viewsA: Relate two dataframes using python logic
The method explode solve this: >>> df_resultado = df1.merge(df2.explode("cat", ignore_index=False), how='left', on=['evento', 'cat']) >>> df_resultado Nome cat evento sim/não resp…
-
0
votes2
answers80
viewsA: Filter column value and extract from these rows in another column the value and write to a new column
The great difficulty of using Pandas is to think that you can do everything in one line. It may be possible, but it is not readable and is difficult to maintain. So let’s split up Creating a test…
-
1
votes1
answer132
viewsA: Pandas error 302; read_html()
The problem is being generated by multiple redirects (error 30X) Looking at HTML, there are many rowspan and colspan; and this will mess up the dataframe. The solution presented uses: requests to…
-
1
votes4
answers285
viewsA: Separate data by values on the line?
Updated on 03/11/2021 Due to the negative score received in my reply, I am updating this post with information that may not be known to everyone. It is possible to run Python code within a script r…
-
0
votes1
answer57
viewsA: Create column based on another dataframe
The solution is to do the merge differently from what is in the commentary Following example: Creating Test Dataframes >>> import pandas as pd >>> df1 = pd.DataFrame({"A": [1, 2,…
-
0
votes1
answer142
viewsA: Doubt Column Label - Seaborn Python
I believe there are several ways, but unfortunately it seems that Seaborn does not implement this. Replacing space with \n would be an option ml_labels = [label.replace(' ', '\n') for label in…
-
0
votes1
answer94
viewsA: How to extract specific data from a python text file and store in a variable
I don’t know how it’s yours arqEspelho.txt then created one to present a possible solution arqEspelho.txt cotia 1 pao 10,00 2 carnes 20,00 ibpt cotia 1 batata 15,00 2 cerveja 172,20 3 calabresa…
pythonanswered Paulo Marques 3,739 -
0
votes1
answer26
viewsA: How can I upload files so they work on other Pcs even if the path to the file is different? (Pygame)
The module os, more specifically your method path is the sollution for this type of case. A huge advantage of using it is the abstraction of the separator between directories import os print(os.sep)…
-
1
votes2
answers325
viewsA: Transforming date object into datetime (year month day) python
Two things in the example you posted: The months are abbreviated in capital letters The months are in Portuguese For the first case, use the title resolves. For the second case you have to use a…
-
0
votes2
answers80
viewsA: Filter column value and extract from these rows in another column the value and write to a new column
I believe you’re looking stack() or unstack() To remember what each one does, the stack will leave your data frame longer, and the unstack wider. Since I don’t have access to the data, follow an…
-
2
votes2
answers41
viewsA: How to extract specific value from received message via Websocket?
If you are sure that the JSON is well assembled, taransforme it into a dictionary First form () >>> texto = '{"codigo": 123, "balance": 10.20, "outro": "qualquer coisa"}' >>>…
-
0
votes1
answer43
viewsA: I have a problem in the relation between two tables in Sqlite using python/Django
It seems your method form is mistaken. On first call I suggest changing the name of the method to something more intuitive for understanding (e.g. cadas_cidadao) @login_required() def…
-
0
votes2
answers88
viewsA: Django/Python primary key generator with low collision risk and good performance
Hashing uuid will generate a much smaller key with a huge possibility of not conflicting import uuid import base64 def get_pk(): pk = hash(uuid.uuid4()) return pk Output example: >>>…
-
4
votes3
answers326
viewsA: Find a button using Xpath Selenium
Avoid using the find_element_by_xpath, because any modification in the layout page will break your script. Give preference to: find_element_by_id find_element_by_name find_element_by_class (not…
-
3
votes2
answers88
viewsQ: Replacing Nan values with the subsequent not Nan of another column
I have a Dataframe with some columns (I’m only representing two in this post). I need to fill the Nan of one column with certain values of another. See below: Creating the Test Dataframe…
-
1
votes2
answers94
viewsA: how should I do for the python code I made for lottery did not repeat the numbers on the same when I put 5 pair and 1 odd to give the game result
Thinking that you have the numbers set from 1 to 60. I believe that creating the set of pairs and the set of odd ones before saves a lot of trouble import random pares = range(2, 61, 2) impares =…
python-3.xanswered Paulo Marques 3,739 -
0
votes1
answer37
viewsA: Validate upload of csv files
I believe you can do this in your method forms.py as below class UploadArquivo(forms.ModelForm): EXTENSOES = ['csv'] class Meta: model = PresencaProf fields = ('evento', 'data', 'upload_csv',) def…
-
1
votes1
answer33
viewsA: Make a query with pymongo filtering by a string ignoring uppercase and minuscule letters
The most correct way would be to create an index that is case insensitive Creating the collection db.createCollection("nomes", { collation: { locale: 'pt_BR', strength: 2 } }) Creating index…
-
3
votes3
answers37
viewsA: Send template data to database
I would make the view a little different. I believe the problem is there. def adiciona_professor(request): if request.method == 'POST': form = AdicionaProfessor(request.POST) if form.is_valid():…
-
2
votes2
answers172
viewsA: Select Dataframe lines based on list of values for a column
Another solution is to use the method isin() Creating Dataframe for Testing >>> import pandas as pd >>> df = pd.DataFrame({'prod':["a","b","c","d","e","f","g","h","i","j"],…
-
1
votes1
answer73
viewsA: Return on screen a database information with Python
Let’s walk Install the library pip install mysql-connector-python Connecting to the bank import mysql.connector mydb = mysql.connector.connect( host="db_host", user="usuario", password="senha" )…
-
2
votes1
answer71
viewsA: Sum values of a string by assigning values to letters (Python)
For the specific case, this solves str = 'ABCD' dic = {'A' : 71, 'B' : 103, 'C' : 115, 'D' : 129} soma = 0 for l in str: soma += dic.get(l, 0) print(soma) The above result is 418 The fact of using…
-
4
votes1
answer30
viewsA: Django: How to prevent date field conflicts in admin
You can create a form with validation Please modify the Vagaadmin @admin.register(Vaga) class VagaAdmin(admin.ModelAdmin): form = VagaForm list_display = ('titulo', 'data_inicio', 'data_fim') Create…
-
0
votes1
answer52
viewsA: Load multiple Amazon S3 files
The following change should work. bg = s3.Bucket("bucket") objects = bg.objects.filter(Prefix="bucket/") obj_summary = s3.Bucket('bucket').objects.all() file_list = [] for obj in obj_summary: print…
-
2
votes1
answer63
viewsA: How to change duplicate data in a dataframe?
You can rename duplicates yes. See below Creating Dataframe Test >>> import pandas as pd >>> df = pd.DataFrame({"frutas": ["banana", "goiaba", "laranja", "banana", "uva",…
pythonanswered Paulo Marques 3,739 -
0
votes1
answer15
viewsA: Copy a Mongodb collection using pymongo and paste it into another collection
What you described would only be part of the code Something like this is missing: for doc in source: destination.insert(doc) Note This process will be slow for large collections. Use the very…
-
0
votes6
answers3379
viewsA: How to find out if the year is leap in PHP?
In a row, you can check by formatting the date with 'L' (Leap year) echo (date('L', strtotime("$ano-01-01")) ? 'SIM' : 'NÃO'); Where $ano is the year you want to test. See more parameters here…
-
0
votes1
answer54
viewsA: Python - Dictionary - Writing and reading correctly
I believe the problem is in the line below: AmpTime.update({'E_Cell_'+str(col+1): Amp, 't_Cell_'+str(col+1): t}) You can change to: AmpTime['E_Cell_'+str(col+1)] = Amp AmpTime['t_Cell_'+str(col+1)]…
-
0
votes1
answer47
viewsA: Fetch value of a condition on lines and separate into a new dataset
Whereas the condition described below is true: For each row, columns have either the same value or Nan Therefore, it is enough to average them, because the method mean ignore Nan Example…
-
0
votes1
answer81
viewsA: Python 3 - CSV to Excel conversion problem with list output
Documenting the solution suggested in the comment import PyPDF2 import pandas as pd from openpyxl import Workbook, load_workbook import string import csv…
-
2
votes2
answers97
viewsA: How do I filter a Dataframe row by knowing a String value from one of its columns?
Take the example: Creating Dataframe Example >>> import pandas as pd >>> df = pd.DataFrame({"frutas": ["banana", "laranja", "pera", "uva", "banana", "pera"], "codigo": ["um",…
-
0
votes3
answers64
viewsA: How to receive a list of each date between two dates in python
Using the library datetime from datetime import date, timedelta data_inicio = date(2021, 1, 1) data_fim = date(2021, 2, 3) delta = data_fim - data_inicio lista_datas = [] for i in range(delta.days +…
pythonanswered Paulo Marques 3,739 -
1
votes2
answers128
viewsA: Rules and Exceptions in htaccess
One possibility is to create the same conditions for each rule RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^login/?$ /login.php [L]…
-
0
votes1
answer33
viewsA: Output of np.Where only back a value
There is a way... Loads variables import pandas as pd import numpy as np Creates dataframe database =…
-
0
votes1
answer202
viewsA: How to add columns of different pandas dataframes?
If you don’t have more than a month in the daily and monthly tables the solution can be: concatenate the dataframes group by imsi and operator sum columns value and cont See below: Create Test…
-
0
votes1
answer31
viewsA: Problem with scope of variables in child class
I understand that there are two possible solutions in your case to share the same variable (in this case self.ids) in two classes: Use inheritance between classes with class attribute Singleton…
-
1
votes1
answer77
viewsA: Cumulative sum of data in new python column
I believe what you need is the method cumsum() Take the example: Creating Dataframe >>> import pandas as pd >>> df = pd.DataFrame({"A": [10, 20, -5, -10, 20]}) >>> df A 0…
-
4
votes2
answers55
viewsA: How to save a dictionary to two independent objects in Python?
In Python 3.9 you have the pipe union "|". dic4 = dic1 | dic2 In previous versions you can do the seginte: dic4 = dic1.copy() dic4.update(dic2) The need for the copy is due to the fact that…
-
2
votes2
answers88
viewsA: How to save the output (stdout) of another program to a file using Python?
In another answer you will find the use of subprocess, much more elegant that the answer I present here. However, this is much simpler. import os def save(filename, comando): comando_completo =…
-
0
votes2
answers221
viewsA: Creating an Entry formatted for CPF in Python (Tkinter)
I adapted the program from here and worked well. Note 1 Imagining this CPF 11.111.111-11 - The same would have to be entered as 011.111.111-11 Note 2 ENTER must be given for the field to be "read"…
-
0
votes2
answers100
viewsA: Search between two dates in Django
Based on comments and post editing: Generally speaking, there are three ways to pass data to a view: In the URL path (eg.: https://www.seu_site.com.br/livros/10) As argument in the URL (eg.:…
-
2
votes1
answer31
viewsA: Creating email with text and HTML does not work | Email spacing
Replace the \n for <br> Explanation: you opted for the mail.HTMLBody. If the body (body) email is HTML, you should use HTML tags. I hope it helps…