Posts by AlexCiuffa • 2,402 points
102 posts
-
1
votes1
answer113
viewsA: What is the best way to use threading in this example?
One solution is to pass each thread a continuous part of the list, such as [..., n, n+1, n+2, ...] and make each Thread assemble a text to be printed. Then each Thread prints its own text.…
-
1
votes1
answer50
viewsA: optimize python code snippet
The column Dia is in the format '%Y-%m-%d'. The first step is to transform to the date type: dforigin.Dia = pd.to_datetime(dforigin.Dia, format='%Y-%m-%d') And then format the way you want:…
pythonanswered AlexCiuffa 2,402 -
0
votes1
answer52
viewsA: Percentage of Video Game Genres in Spyder
Given a list, lista = ['plataforma 1', 'plataforma 1', 'plataforma 2'] When we do: for valor in lista: print(valor) The exit is: plataforma 1 plataforma 1 plataforma 2 In your code is: for porc in…
-
1
votes2
answers469
viewsA: Sum recursive sequence
Datum: Soma(x,n) = x + x^2 / 2 + x^3 / 3 + ... + x^n / n Notice that: Soma(x,n) = x + x^2 / 2 + x^3 / 3 + ... + x^n / n # |----------------------------| Soma(x,n) = Soma(x,n-1) + x^n / n defining…
-
1
votes1
answer126
viewsA: How to create a CNN model correctly in Keras?
About OOM Problem of OOM (Out Of Memory) happens when the available memory is not enough. When using images, the most common architecture involves Convolutions and Poolings, as this decreases the…
-
0
votes3
answers1465
viewsA: Itemgetter - Sort list of dictionaries - Python
One solution is to take the relevant information out of dictionaries and then sort. #formo uma nova lista só com as informações que interessam e sem o dicionário lista_sem_dicionario =…
pythonanswered AlexCiuffa 2,402 -
0
votes2
answers123
viewsA: How to make an associative matrix in python 3?
python has the function Chr, it returns a character from an integer. For the uppercase alphabet, this number starts with 65 (A) and ends with 90 (Z)). >>> chr(65) 'A' >>> chr(90)…
-
0
votes2
answers143
viewsA: Find arrays with the shortest distance
I was able to solve by calculating all distances and storing them. Then, I get the ids of the lowest values from the distance list and the returns. def pega_n_vetores_mais_proximos(array_objetivo,…
-
1
votes2
answers143
viewsQ: Find arrays with the shortest distance
I have a array_objetivo and would like to find the id and the distance (Euclidean in this example) of n arrays closer to him that are in array_all. Following are examples of arrays. array_objetivo =…
-
0
votes3
answers497
viewsA: Convert string into a list where each element in the list is 3 characters from my initial string
The for i in range() receives as parameters an initial value, a final value and a value to iterate. Summarizing: for i in range(val_inicial, val_final, iterador). The value of i is iterated to a…
-
0
votes1
answer231
viewsA: Compare string PANDAS Data Science
If the comparison is to see the number of occurrences of each type, Acidente and Incidente, and plot a bar graph, it is possible to use the function hist of the pandas themselves: df['Investigation…
-
1
votes1
answer39
viewsA: Multilayer Perceptron Two-Layer Code Problem
The problem is not whether values are integer or not. The format of y are different. y = np.array([[0], [1], [1], [0]]) >>> y.shape (1, 4) Now with the y of its code (which by the way is…
-
1
votes3
answers1073
viewsA: How to change CSV in Python and Pandas?
One way to do with pandas is to use the function apply(). df['Intervalo']=df['IDADE_INGRESSO'].apply(lambda x: 'menor_21' if x<21 else ('menor_24' if x<24 else 'maior_24')) If your rule is…
-
4
votes1
answer2195
viewsA: How does the "argmin()" and "argmax()" function of Numpy work?
The functions argmax and argmin return, respectively, the indices of the highest and lowest value of an array. A caveat is that if two equal values are greater (or smaller), they return only the…
-
4
votes3
answers90
viewsA: Problem editing a list in Python 3
Do for l in lista: l = l.split() Is similar to do: for i in range (0,len(lista)): l = lista[i] l = l.split() Which is equal to: for i in range (0,len(lista)): l = lista[i].split() Note that only the…
-
2
votes1
answer2054
viewsA: Accessing an element in pandas dataframes
The dataframe created by your code has the following form: 0 1 2 0 2019 0000 protocolo 1 2020 1111 pedido Making df = df.sort_values(by=['2019', '0000']), you are trying to access the name columns…
-
1
votes5
answers6310
viewsA: How to stop the end='' command in Python
Another solution is to prepare a string and print everything at once tabela = ('Palmeiras', 'Flamengo', 'Internacional') s = '' for time in tabela: s += time + ' ' print(s[:-1]) # a parte `[:-1]`…
-
0
votes1
answer654
viewsA: How to make a chart from a python dictionary
With matplotlib is quiet to do. import matplotlib.pyplot as plt If your dictionary is an occurrence counter, just do dicionario = {2018:30, 2019:28, [...] ,2024:3} plt.bar(dicionario.keys(),…
-
1
votes1
answer834
viewsA: Python - Count values within another count of values in a dataframe?
As each column has a list, the best solution I could think of was to make a dictionary of the problems and iterate the dataframe. Each problem has a dictionary with a counter of each solution that…
-
13
votes4
answers4140
viewsA: What is bias in neural networks?
Simply put, Bias is an input of value "1" associated with a weight "b" in each neuron. Its function is to increase or decrease the net input in order to translate the activation function on the…
artificial-intelligenceanswered AlexCiuffa 2,402 -
0
votes2
answers52
viewsA: How to show a list of values of a register applying filters on numeric values?
1) When you compare the i, you are comparing the index of the list, not the values. To compare the values, use lista[i]; 2) Its function has a print(lista) within the for, i.e., for each iteration…
pythonanswered AlexCiuffa 2,402 -
1
votes1
answer49
viewsA: Python - Doubt about imports in the creation of libraries
Need to import again: #arquivo teste1.py import random print ("Olá") #arquivo teste2.py import teste1 for i in range(0,5): print(random.randint(0,i)) When I run by the prompt:…
-
2
votes4
answers232
viewsA: Transform a numeric string into a list of python numbers
entrada = ['[11, 14]', '[8, 17, 18, 24, 29, 37, 44, 49, 51, 55, 62, 63, 64, 76, 82, 84, 93, 97]'] saida = [] for string in entrada: #tiro o '[' e o ']' e depois separo pelas…
pythonanswered AlexCiuffa 2,402 -
0
votes1
answer115
viewsA: Rank the contents of a Python list 3
lista = [6,4,3,9,1] #lista com os valores em ordem decrescentes e sem valores repetidos lista_decrescente =…
-
2
votes2
answers120
viewsA: Table grouping
One solution I found was: take the unique values of the columns 'users_ID_User' and 'Material', generate a new data by means of a dictionary and insert this data with an append in another dataframe.…
-
2
votes1
answer428
viewsA: Find common values in two different dataframes
Starting from these two dataframes: >>> print df1 dados 1.1 1.123 2.2 1.567 3.3 2.001 4.4 2.345 >>> print df2 dados 1.0 1.12 2.3 1.56 3.5 2.00 I calculate the distance of two…
python-2.7answered AlexCiuffa 2,402 -
1
votes1
answer466
viewsA: Function to create Column
Its function cria_colunas receives a string. Do df[string_campanha] causes a column to be searched in the df with the name string_campanha. Since there is no such column, it generates the error…
pythonanswered AlexCiuffa 2,402 -
6
votes1
answer398
viewsA: Testing Mega Sena Games
There are 50.063.860 possibilities of results in this game of 6 numbers. A chance to come out a combination [a1,a2,a3,a4,a5,a6] expected is to 1/50.063.860 = 0,00000002 which corresponds to…
python-3.xanswered AlexCiuffa 2,402 -
2
votes3
answers5205
viewsA: Python - Select 2 columns from a DF and sort them
From this Dataframe: # -*- coding: utf-8 -*- import pandas as pd d = {'Sex':['female','female', 'female', 'female', 'male', 'male','male','male'], 'Age':[38.0,26.0,4.0,14.0,33.0,24.0,7.0,16.0]} df =…
python-3.xanswered AlexCiuffa 2,402 -
3
votes1
answer3253
viewsA: (Pandas) - Group and summarise by date
Given that Dataframe: # -*- coding: utf-8 -*- import pandas as pd d = {'Data': ['01/02/2017','06/02/2017','03/02/2017','02/02/2017','01/02/2017'], 'Acidentes': [0,2,1,0,1], 'Vitimas': [0,1,0,0,2]}…
-
4
votes2
answers1260
viewsA: How to paste a dataframe over a pre-formatted Python worksheet?
import pandas as pd from openpyxl import load_workbook df = pd.DataFrame(data={'Dados1': ['Ola','tudo','bom']}) #carrego o Excel com o template pré-formatado 'template.xlsx' book =…
-
1
votes1
answer65
viewsA: How to use indices of two arrays to form a third array?
Only use the for... Let A and B be: A = [[0,2,1],[1,2,0],[2,1,0]] B = [[1,0,2],[2,1,0],[2,0,1]] Then we make: C = [] for i in range(len(B)): linha_C = [] for j in range(len(B[i])):…
pythonanswered AlexCiuffa 2,402 -
0
votes3
answers1281
viewsA: Python dictionary
A little late, I would like to add the functionality to search for ready expressions like 'good morning'->'good Morning' differentiating 'Good trip'->'good trip', ie to go beyond word-for-word…
pythonanswered AlexCiuffa 2,402 -
2
votes2
answers136
viewsA: How to transform a list [['a'], ['b']] into a string: ab
(Answering the title, because the rest did not understand anything, please edit and improve the question) From a list, we can concatenate its values in various ways such as: lista = ['o','l','a']…
-
2
votes2
answers110
viewsA: How to associate objects to the vertices of a graph?
See if this solution pleases you: class Ambiente: def __init__(self, titulo, descricao, id): self.titulo = titulo self.descricao = descricao self.id = id A = Ambiente('Sala de maquinas', "A sala…
-
0
votes1
answer62
viewsA: Add historical
#Pego os anos anos = gd['DATA_CRIA'].tolist() #OU anos = gd['DATA_CRIA'].values #ordeno os anos por precaução anos.sort() dic_ano = {} soma_frota = 0 for ano in…
pythonanswered AlexCiuffa 2,402 -
1
votes2
answers159
viewsA: Indexing error when separating line information
One solution is to use: def cria_colunas(string_campanha): lista = string_campanha.split("|") if len(lista) == 0: return '', '', '' elif len(lista) == 1: return lista[0], '', '' elif len(lista) ==…
-
2
votes3
answers1001
viewsA: (Python) Find words with total vowels being even
See if that helps you. def frases(): vog="aeiou" dig="0123456789" sd=0 sv=0 vp=[] matriz_palavras_vogais_pares = [] f = str(input('Digite uma frase: ')).lower() while f != '': palavras_vogais_pares…
-
0
votes3
answers1564
viewsA: Python variable reference return
What we want is basically to make list_2 = list_1 without list_2 being a reference to list_1, that is, we want to copy only the values. Another solution besides copy() is to use deepcopy function():…
-
0
votes2
answers247
viewsA: How to sort a list by the number of occurrences? In Python
If you don’t want to use libraries, here’s an idea using dictionaries: First I create a dictionary with occurrences lista = [1,1,2,3,3,3] ocorrencias = {} for numero in lista: if numero in…
-
1
votes3
answers1348
viewsA: How to calculate the median of a large amount of values?
I would like to suggest another approach. If the numbers are integer or with a few decimal places, many of them can be repeated, then we can count the number of occurrences of each number one with a…
pythonanswered AlexCiuffa 2,402 -
1
votes3
answers1348
viewsA: How to calculate the median of a large amount of values?
In this type of problem we have to be very careful with running time and memory. Working with lists can be a problem. For now I suggest this solution. 1) Read the file line by line and, while…
pythonanswered AlexCiuffa 2,402 -
2
votes1
answer3264
viewsA: Change Column Data using Pandas
From the example: import pandas as pd d = {'PSG':['AAA', 'BBB', 'CCC', 'DDD'], 'CLASS':[1,2,3,1]} df = pd.DataFrame(data=d) >>> print df CLASS PSG 0 1 AAA 1 2 BBB 2 3 CCC 3 1 DDD We created…
-
1
votes2
answers558
viewsA: Imports into __init__.py file
(Another example, although they have already answered) They help with code organization. We usually import more commonly used functions and classes into __init__.py. Given this architecture:…
-
0
votes3
answers340
viewsA: How to add values of a json request in python?
You have multiple dictionaries within a list, so we can access these dictionaries with a for: req = [{"amount": 0.1}, {"amount": 2},{"amount": 145},{"amount": 5.84}] soma = 0 for dic in req: soma +=…
pythonanswered AlexCiuffa 2,402 -
0
votes1
answer94
viewsA: Quantity in a dataset
I assumed you are using Pandas and Dataframe. Starting from that: import pandas as pd anos = [2008, 2009, 2010] d = {'DISTANCIA': [12.3, 33.3, 11.1, 43.4], 'DATA_CRIA': [2008, 2008, 2009, 1909]} df…
pythonanswered AlexCiuffa 2,402 -
1
votes2
answers4781
viewsA: Sum of column totals
I assumed you’re using pandas. Anyway, starting from this: import pandas as pd d = {'Distritos': ['Local1', 'Local2'], '2017': [30, 40], '2018': [50, 60]} df = pd.DataFrame(data=d) >>>…
pythonanswered AlexCiuffa 2,402 -
3
votes2
answers135
viewsA: Compare Python index independent lists
I thought of the following solution: 1) Take names as a list of names def pega_nomes_de_dicionario(lista): lista_nomes=[] for dic in lista: lista_nomes.append(dic['name']) return lista_nomes…
-
2
votes2
answers468
viewsA: Concatenation of multiple lists with Python
If the problem is just concatenating the lists, the @Gustavorps answer solves. If the problem is that there are lists within lists, such as: disciplina1 = [1, [2,3]] disciplina2 = [[4,5], 6,…
-
1
votes1
answer7854
viewsA: How to insert a line in a Dataframe Pandas in the middle of other lines?
Assuming we have this Dataframe: d = {'nome': ['maria', 'Pedro', 'Mario'], 'idade': [30, 45, 36], 'estado': ['SP', 'BA', 'RJ']} df = pd.DataFrame(data=d) >>> print df estado idade nome 0 SP…