Posts by lmonferrari • 3,550 points
179 posts
-
0
votes1
answer20
viewsA: speech_recognition worthless
You have to treat Unknownvaluror Requesterror Timeout error: import speech_recognition as sr import os while True: recognizer = sr.Recognizer() mic = sr.Microphone() with mic as source: print('#…
pythonanswered lmonferrari 3,550 -
1
votes1
answer242
viewsA: How to collect Tweets in real time with tweepy in Python
Importing the tweepy: import tweepy Over screve tweepy.Streamlistener: class MyStreamListener(tweepy.StreamListener): def on_status(self, status): print(status.text) Credentials: consumer_key =…
-
1
votes2
answers41
viewsA: How to get the X coordinate if the Y condition is met with Numpy?
The values: a = np.array([ [0.57946528, 2. ], [0.35226154, 0. ], [0.26088698, 0. ], [0.56560726, 1. ], [0.41680759, 1. ], [0.55771505, 0. ], [0.8501109 , 0. ], [0.76229916, 1. ], [0.50357436, 0. ],…
-
0
votes2
answers81
viewsA: Insert the values of an N-size vector into the same Python line
If what I understand is correct, you want to receive the values without having to use a repeat structure, you can use map + split and turn into a list: n = int(input('Digite valor para N: ')) # os…
pythonanswered lmonferrari 3,550 -
1
votes3
answers148
viewsA: Count recurrences in a list
Using your code/reasoning, you can use a "filter" (new list): n = int(input()) lista = [] for c in range(n): lista.append(int(input())) filtro = [] for i in lista: if i not in filtro:…
pythonanswered lmonferrari 3,550 -
0
votes2
answers189
viewsA: filter dataframe by python line
You can use groupby + max Data types in excel file: df.info() Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 DT_REFER 6 non-null datetime64[ns] 1…
-
6
votes1
answer84
viewsA: How to select samples in R
You can use replicate + sample with replace false: a <- replicate(100, sample(x = x, size = 10, replace = F)) The replicate will replicate the number of times you stipulate the function within…
ranswered lmonferrari 3,550 -
3
votes2
answers275
viewsA: How to write a program that fills a 10-position vector with random integers between 0 and 20?
You can use np.random.randint to generate the random number, in which case the numbers can repeat. This returns a list: v = [np.random.randint(0, 21) for i in range(10)] type(v) list This returns a…
-
1
votes1
answer120
viewsA: How to verify null value in rows in a dataframe column?
You can use the fillna() with the forward Fill filling method' df['year'].fillna(method = 'ffill', inplace = True) Entree: year value 0 2000 1 1 NaN 2 2 NaN 3 3 NaN 4 4 NaN 5 5 NaN 6 6 NaN 7 7 2001…
-
0
votes2
answers46
viewsA: Print a new vector by changing the order of the elements of the original vector
You can use the Random package sample: from random import sample v1 = [2,51,68,10] def embaralha(x): return sample(v1, len(v1)) v2 = embaralha(v1) print(v2) One of the possible exits: [51, 68, 10,…
-
1
votes1
answer333
viewsA: Frequency table - Python
This is just one of the ideas you can use: Copying the dataframe to the original to be intact: df1 = df.copy() Adding up the lines: df1['Total'] = df1.sum(axis = 1) Adding the columns together and…
python-3.xanswered lmonferrari 3,550 -
0
votes1
answer74
viewsA: How to ask the user to create an np.array vector?
Import of numpy import numpy as np Creating the np array a = np.array([]) Adding elements, you can do this with while, with an input only and mapping the entries, here follows an example with for:…
-
1
votes3
answers166
viewsA: how to find the indexes of an item that repeats in a list in Python
You can create a list directly using list comprehension: l = [1,6,6,2,3,6] l2 = [ i for i in range(len(l)) if l[i] == 6 ] We check by index if the 6 is contained, if you add the index to the list.…
-
1
votes1
answer580
viewsA: Playing mp3 music in Python
If mp3 is in the same script folder: from pygame import mixer mixer.init() mixer.music.load('brain_damage.mp3') mixer.music.play() If the mp3 folder is at the same level as the script you add a .:…
-
0
votes1
answer31
viewsA: Flickrapi and photos of a specific user with Python
Repurposing your code Importing the necessary libraries: import flickrapi import urllib.request from PIL import Image Authentication: api_key = u'API_KEY' # passando em formato unicode api_secret =…
-
5
votes4
answers406
viewsA: Return the missing element from a list of integer numbers
You can compare if the next element is the sum of the current element + 1, if different we add the current item + 1 (which should be the real value) to the list, which is within the function, and at…
pythonanswered lmonferrari 3,550 -
1
votes3
answers169
viewsA: Doubt about Python data output
As you have already got the first part, to print the numbers on one side of the other you can use the Join: print(' '.join(str(i) for i in range(1,21))) The join will iterate over the elements…
-
1
votes2
answers675
viewsA: What is RDD (resilient Distributed dataset)?
The main abstraction that Spark offers is a resilient distributed data set (RDD), which is a collection of partitioned elements at cluster nodes that can be operated in parallel. In Spark there are…
-
0
votes2
answers1329
viewsA: Change size of Plot area
import numpy as np import matplotlib.pyplot as plt Creating dummy data: X = np.arange(1,20) Y = X * np.random.randint(19, 40, 19) Here is the line that does the job of changing the size of the Plot:…
-
0
votes1
answer463
viewsA: Google Gspread colab and pandas
... # get_all_values gives a list of rows. rows = worksheet.get_all_values() print(rows) ... Pandas import import pandas as pd One output is to take the first row and turn into columns: df =…
-
1
votes1
answer181
viewsA: Linear Regression Evaluation and Graph Problem
Importing the read_csv from pandas import read_csv Creating the dataframe and deleting the date column df = read_csv('./Consumo_cerveja.csv') df.drop(columns = 'Data', inplace = True) Removing the…
-
1
votes1
answer89
viewsA: Only she needs to calculate the result of this formula for various values of x
You can create a function where the parameter is x to do the calculations: def f(x): return (x**2) - (4*x) + 5 Here you receive user values: x1 = int(input('Inicial: ')) x2 = int(input('Final: '))…
-
0
votes1
answer268
viewsA: Inserting in a python sqlite3 database by a class
In savedb, instead of: self.cursor.commit() Try: self.banco.commit() Cursor does not have the attribute commit() Edit To avoid the error that the database returns saying that the table already…
-
3
votes1
answer73
viewsA: How to place the values of the discrete Y scale in ascending order?
Using the data you put in the question: ID Home range (m) #MB02 156.148 #MB03 247.969 #MB04 156.148 #MB05 92.400 #MB06 1022.954 #MB07 156.148 #MB08 672.731 #MB09 156.148 #MB10 594.328 #MB11 554.670…
-
0
votes4
answers975
viewsA: Return a list from another list in Python
You can use a function that already returns the list. Here we define the list and what will be the value of n (this typed by the user): lista_numeros = [1,2,3,4,5,6,7,8] n = int(input('Valor para n:…
pythonanswered lmonferrari 3,550 -
1
votes1
answer66
viewsA: What could I do for that except not to interrupt my Else?
Keeping (almost) all your code, you can pass the continuar = input('Deseja continuar? Sim ou não:').lower() into while, that way at each iteration it will ask if you want to continue and will not go…
-
0
votes4
answers361
viewsA: How to count occurrence of strings within a dictionary made up of lists in Python?
In case you don’t want to split it two ways, like you did here: pesquisa = {'PEDRO': ['FANTA',5,'PEPSI',4],'ANA': ['SPRITE',5,'COCACOLA',4]} def relatorio_avaliadores(): print('Relatório de…
-
0
votes1
answer21
viewsA: Doubt Python 3 Selecting items from a dataframe
It is the 'same thing'. You have the two possibilities to access the same things. The author of the exercise wanted to show you that you can do one way or another that the result will be the same.…
python-3.xanswered lmonferrari 3,550 -
3
votes4
answers150
viewsA: Calculate percentage of an item in a group per year in R
A possible solution would be to pivot the data frame: library(tidyverse) dados2 <- pivot_longer( data = dados, cols = starts_with('20'), names_to = 'Ano', values_to = 'Valores' ) Then we group…
-
0
votes2
answers170
viewsA: How to put lines on a chart and bar?
I’d like to know how to insert lines in a bar graph. You can insert lines using geom_line(): ggplot(teste, aes(x = Periodo, y = Valores, group = 1)) + geom_bar(stat='identity') + geom_line()…
ranswered lmonferrari 3,550 -
0
votes1
answer1122
viewsA: Python/Selenium - no such element
Since I don’t have access to the page, try this way: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions…
-
-1
votes1
answer202
viewsA: How to generate a horizontal multiple graph using python
Imports: import pandas as pd import matplotlib.pyplot as plt Loading the data frame: df_escolaridade = pd.read_csv('./dataframe.csv', index_col=[0]) df_escolaridade.drop(columns = 'Código', inplace…
-
2
votes1
answer123
viewsA: Displaying only integer values on X-axis in matplotlib chart
You can use plt.xticks: import matplotlib.pyplot as plt %matplotlib inline X = [k for k in range(20)] y = rmse_val plt.xticks(range(len(X))) plt.plot(X,y,color='green' , marker='o', markersize=2,…
-
1
votes1
answer24
viewsA: How can I save these two python functions in separate files?
You can use open('nome_do_arquivo.txt','w'), f.writelines() and f.close(). That’s for every file you want to write. print ('Olá.\nPor favor, digite um primeiro valor para verificar os números primos…
-
0
votes4
answers140
viewsA: How to print more than a maximum number of a list
You can use list comprehension and use the zip function: aluno = [] nota = [] while len(aluno) < 5: aluno.append(input('Digite o nome do aluno: ')) nota.append(int(input('Digite a média final do…
-
1
votes2
answers165
viewsA: How can I get the highest value of a matrix with Lambda function in Python
You can iterate your matrix within the second reduce argument: from functools import reduce matriz = [[4, 2, 56], [7, 46, 10], [3, 89, 2]] print(matriz) result = reduce((lambda x , y: x if (x >…
-
1
votes3
answers510
viewsA: Use Selenium without opening browser
If you don’t need to be using Selenium + Webdriver you can use the requests + Beautifulsoup: Importing required libraries and creating header to not receive 403 error (Forbidden) import requests…
-
1
votes2
answers24
viewsA: How do I return to "double" from the original df?
df <- data.frame(valores = as.factor(c(1.1, 2.0, 3.3, 1.1, 1.0, 2.0))) df$valores_num <- as.double(as.character(df$valores)) df$valores_num You can try converting to 'string' first and then as…
ranswered lmonferrari 3,550 -
2
votes1
answer1220
viewsA: I need to select the last Dataframe value to calculate the value of the next row in the same column
To select the last element you can use iloc: df['Mínimo da Temporada'].iloc[-1] Exit: 10 Edit To add the value to the Mint variable: mint = df['Mínimo da Temporada'].iloc[-1] print(mint) 10…
-
0
votes1
answer141
viewsA: Python replace values with others in combination
I do not know if I understood the question very well but it follows a possible solution. Code: positivos = [0.0195, 0.0194, 0.0193, 0.0193, 0.0196, 0.0205, 0.0204, 0.0212, 0.0202, 0.0189, 0.0190,…
-
0
votes2
answers51
viewsA: How to find out how many times a certain level is repeated in a specific column (factor) of a data.frame?
I believe Summary function works for what you want. summary(df$variavel) As quoted in the comment by Willian the function table() also solves your problem. table(df$variavel)…
-
2
votes1
answer37
viewsA: Create loop and move to arguments of a function?
You can do using enumerate: tamanho_celula = [30, 140, 90, 55, 60, 40] for col, tamanho in enumerate(tamanho_celula): storage.tableWidget.setColumnWidth(col, tamanho) In the first line you create a…
-
0
votes3
answers52
viewsA: How to fill out a list?
You can use list comprehension: lista1 = [0, 3, 7, 10, 15] lista2 = [0, 1, 2, 3, 4, 5, 6, 7,8 ,9 ,10 ,11, 12, 13, 14, 15, 16, 17, 18, 19, 20] lista3 = [item if item in lista1 not in lista2 else…
-
0
votes2
answers190
viewsA: Label data in column charts at "Dodge" position in R
You can use position = position_dodge(width = 1) Code: df2 %>% ggplot(aes(Ano, n, fill=Condicao))+ geom_bar(stat = 'identity', position="dodge") + geom_label(aes(Ano, n, label= n), position =…
-
0
votes2
answers166
viewsA: AND OR PANDAS CONDITION
A more intuitive way to do this is by using the query command, but in terms of performance is not as fast as a pandas' isin: Yes or No df.query("col1 == 'sim' or col1 == 'nao'") Yes and No / this…
pandasanswered lmonferrari 3,550 -
0
votes2
answers313
viewsA: Fill list and finish python loop
In your example there are some errors: end is not string you are comparing end with a variable that contains an integer while(!=end) already indicates if you type 'end' in the input it will break…
-
4
votes2
answers195
viewsA: Recursiveness using Python
Calling the function itself before the print works: def sequencia_de_numero(number): if number < 0: return -1 sequencia_de_numero(number - 1) if number % 2 == 0: print(number, end=' ') Then just…
-
0
votes2
answers284
viewsA: Convert pandas dataframe column with string array (Python)
You can use the pandas applymap together with isinstance: df.applymap(lambda x: x if not isinstance(x, list) else " ".join(x)) The data frame receives the value of x without modifications if it is…
-
1
votes1
answer57
viewsA: Try no for - PYTHON
An alternative is to initialize the teste1 variable as a string and check its type, in case the casting to float goes wrong it goes back to the starting line of while, until the person enters…
-
0
votes3
answers529
viewsA: Product between scalar and array
If you do not want to use numpy you can solve with list comprehension: a = [0.4850045, 0.45512111] b = [-0.03116616] [(x * y) for x in a for y in b] Exit: [-0.015115727847719999,…