Posts by Lucas • 3,858 points
153 posts
-
1
votes0
answers51
viewsQ: How to apply Transform to two variables in pandas?
I would like to create a new variable which is the scalar product of two variables in a sub-group of my dataframe. I know that when I want to create a group-level variable, I can use the method…
-
4
votes1
answer145
viewsA: How to transform an array with strings(list) into an integer array in Python?
One Line Solution: V2=[round(int(k)/11) if k.isdigit() else k for k in V1[0].strip().split(" ")] I used list comprehension to create the new list. The conditional checks if substring is a digit…
-
3
votes2
answers53
viewsA: How to change abbreviated values in a DF using Pandas in Python
One option is to define a function, use list comprehension and iterate over df.columns: def transform_str(value:str): return value.replace(",","").replace("B","000000").replace("T","0000000000") for…
-
1
votes1
answer23
viewsA: How can I line a Pandas dataframe from a list that contains variables?
One possibility is to create Dataframe from a list dictionary, as indicated in this question. In your case, we would have: import pandas as pd import random Colunas = ["A","B","C","D"]…
-
1
votes1
answer52
viewsQ: How to do k-fold validation when I change the cut-off of the model?
When I report metrics from a machine-Learning model I always use k-fold validation. Here’s an example of implementation: import pandas as pd import numpy as np from sklearn.model_selection import…
-
4
votes2
answers55
viewsA: How to calculate the average for groups and identify the maximum value?
If I understood what you need, it is possible to solve using the method agg: tab =df.groupby(by='Month').agg({'Billed':'sum'}) #ordenando a tabela tab=tab.sort_values('Billed',ascending=False) tab…
-
3
votes2
answers58
viewsQ: How does the numpy Prod method work?
I’ve always used the method np.prod as a production operator. So if I want to know the factorial of 5, for example, I simply do: import numpy as np np.prod([5,4,3,2,1]) 120 It turns out I was…
-
1
votes2
answers108
viewsQ: How to get the product to scale two vectors in Javascript?
In python, if I have two vectors, I can get the scalar product using numpy. Following example: x=np.array([2,4,6]) y=np.array([1,3,5]) np.dot(x,y) Returns: 44 I’m looking for an equivalent function…
-
0
votes1
answer58
viewsQ: What is the difference between executable files generated using chmod and those generated from a compilation?
When I use Python on Linux, I usually transform extension files .py executable using the chmod. Example: Filing cabinet user_sum_python.py: #!/usr/bin/env python def user_sum(L): if len(L)==1:…
-
1
votes1
answer64
viewsA: Save MP3 to a specific directory using youtube_dl
There are at least two ways to do this. One is by using the module itself youtube_dl. Just change the argument value outtmpl of filename for 'PATH%(title)s'+'.mp3'. Where PATH is the address you…
-
2
votes1
answer125
viewsQ: What are Assembly Languages (assembly language)?
I was researching which languages are used to build operating systems. It appears that Windows, Mac and Linux use, to a large extent, C and C++. In the same source I found this information, I read…
-
1
votes0
answers42
viewsQ: Is there any difference from Binary search to ordered Binary search on a list?
I’m studying algorithms for Searching and wanted to better understand the difference between Binary search for ordered Binary search. I understood that for both algorithms to work, the list needs to…
-
1
votes0
answers18
viewsQ: What is the point of defining the type of an argument in a function in python?
I imagined that previously defining the type of argument in a function in python would automatically cause the program to return a Typeerror if the user added an argument with different typing than…
-
4
votes2
answers96
viewsQ: How does logic test work with two integers in Python?
I was analyzing a code and came across the following expression: 1 & n >> k Where n and k are integers. For now, I’m focused on the first part of the expression. I’ve never seen a logic…
-
1
votes1
answer30
viewsQ: How to prevent a grid-item from changing size when adding text?
I am developing a small tool that takes a user text and generates an encrypted version (Caesar cipher). I managed to build the layout of the GUI the way I would like using the model grid-container.…
-
3
votes1
answer157
viewsQ: What is the difference between string find and index methods in Python?
I always use the method index to fetch the index of a character in a string in Python. I recently discovered the method find() and I noticed that he does exactly the same thing. Example: name="Alan…
-
-1
votes1
answer54
viewsQ: Is it possible to inherit a limited set of methods from a super class in Python?
I would like to build a class that inherits only a few methods from the mother class, but not all. To understand what I mean, suppose I have two classes, Person and Student: class Person: def…
-
1
votes0
answers17
viewsQ: Is it possible to make small changes to my package without having to change the version in Pypi?
I made a package in python and added it to Pypi. Now, I’d like to update just one error message. When I make more complex updates, I create a new release on Github and update the version in my file…
-
1
votes6
answers37862
viewsA: How to remove characters from a string?
Well, I think the most pythonic solution would be to use the method str.translate: string1 = 'chocolate' string2 = 'oca' char_rep={k: '' for k in string2}…
-
2
votes1
answer648
viewsA: Make a histogram with a Gaussian curve in Python
Since you have the frequency data ready, I believe that you do not need to make use of the functions that create histograms, such as plt.hist of matplotlib and sns.distplot of Seaborn. Anyway, it is…
-
2
votes2
answers445
viewsA: How to concatenate value to a column of a table in csv?
Solution using pandas: import pandas as pd df=pd.read_csv("file.csv", sep=";") df.columns=[k.strip() for k in df.columns] df['Número']=['+244'+str(k) for k in df["Número"]] print(df) Returns: Serial…
-
0
votes0
answers29
viewsQ: How to access the value of an array within a while loop in SQL?
In the database I’m working on there are a number of salary variables that are registered as strings with entries like 0000001155,00. I’m using a combination of CAST and REPLACE to turn these…
-
0
votes1
answer84
viewsA: How to print typed text in a Tkinter GUI on the console?
You did almost everything right, but missed noticing that the text is a attribute of your frame, not the frame itself. Note that, as it stands, your program is printing the object name…
-
2
votes1
answer62
viewsA: How to get the total of combinations between two datasets and the sum of their attributes?
The solution to this type of problem is DataFrame.combine (link to documentation), but how you want to combine columns with different names and make a "distributive" it takes a small workaround.…
-
2
votes2
answers35
viewsA: How to apply a ribbon to a dataframe based on the last characters of each label?
One solution is to create a filter using list comprehension: filtro=[k[-3:]=='BRL' for k in df.A] df=df[filtro] Example with fictitious database: import pandas as pd import random…
-
1
votes2
answers63
viewsA: Is there any way pd. Grouper, how much used for time frequencies, adds lines even when there are no records in a time interval?
A solution is: Create an empty database; Place dates in this database that belong to the desired range but have no information; Fit with the original seat. Follow code with this solution: import…
-
5
votes3
answers77
viewsQ: Is there a bash iterator equivalent to the python enumerate?
It is common situations in which, to iterate, I need not only the elements of a list, but also their respective indexes. In python, this type of iteration is facilitated with the use of iterator…
-
1
votes2
answers97
viewsA: How to filter rows where columns meet consecutive conditions in Python?
One Line Solution: df['promo']=pd.Series([bool(re.search(r'(L|I)(?=[AS])',k)) for k in df.sum(axis=1)]) My idea was to transform the columns into a single column with the concatenation of the other…
-
1
votes1
answer37
viewsA: How to initialize N random vectors, where N is provided by the user?
One solution to this type of situation is to use comprehensilist on: import random x = int(input("Digite o tamando do cromossoma: ")) n = int(input("Digite a quantidade de vetores: ")) saida = []…
-
2
votes1
answer83
viewsA: How to change Threshold from a classification model?
The solution is simply to generate a new predictive vector from the probability vector of the reference class. To get the probability vectors, just do: y_scores=logistic.predict_proba(X_test) For…
-
1
votes1
answer83
viewsQ: How to change Threshold from a classification model?
In addition to providing classes directly, some models of machine Learning generate probability vectors of belonging to each of the classes for each observation in the sample. The class predicted by…
-
1
votes1
answer904
viewsA: How to create bar graph using Dataframe.Plot?
If I understand what you want to do, you don’t need the DataFrame.plot. It’s simpler than that: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("tabela_trabalho2.csv", sep=';' ,…
-
1
votes1
answer1063
viewsA: Customize/customize Python chart caption
What you need is the method plt.annotate and add some parameters in the method plt.legend: import matplotlib.pyplot as plt import pandas as pd names=['A', 'B', 'C', 'D','E','F','G'] df =…
-
5
votes1
answer150
viewsQ: How to remove a file from Git, but keep it locally?
When I have a file on my local computer that I would like not to be uploaded to the repository on Github, I simply create a file .gitignore and add the path file. It so happens that I would like to…
-
6
votes1
answer124
viewsQ: Why is the "in" method for checking if an element belongs to a collection so slow?
I was having a lot of difficulty executing code efficiently and found that the problem was on a line that used the operator in. Then I created a new function that searches for a match in the list of…
-
1
votes2
answers1450
viewsA: How to extract information from table(html) and move to a Dataframe - Using Selenium
A little late, but maybe the answer interests someone else. The problem is that the "Merchandise" line is only defined in html in the first line of each merchandise. Outside the first row, the first…
-
0
votes1
answer93
viewsA: Regex to pick up capitalized words in the middle of a sentence
The solution is to use Negative Lookbehind. So your regex would look like this: '(?<!\.\s)[A-Z][a-z]+' Complete code: const regexp = /(?<!\.\s)[A-Z][a-z]+/g const text = "O Facebook e Twitter…
-
1
votes1
answer59
viewsA: Question about list(zip) command and converting dictionaries to dataframes?
Yes. It is possible to convert dictionaries into DataFrames. In fact, a dictionary with strings like keys and values like list is a ready-made form of a pandas DataFrame. With a dictionary in the…
-
1
votes1
answer28
viewsQ: How do I egrep print the matchlist of a file?
I’m reading a book of regular Expressions where the author uses egrep to show some examples. It happens that when I try to replicate the examples on my computer my output is different from the one…
-
3
votes1
answer77
viewsA: How to extract text from a selected Beautifulsoap element?
Use the method get_text: import requests, bs4,os url = ('https://valor.globo.com/') res = requests.get(url) objSoup=bs4.BeautifulSoup(res.text,features="html.parser") newsValor =…
-
1
votes1
answer167
viewsA: Plot graphing of an algebraic expression in python
It was not entirely clear to me his expression. I made some hypotheses in the implementation below that, I believe, do not compromise the example. First of all, if e is the Euller constant, the…
-
8
votes1
answer147
viewsQ: What is the equivalent of Python’s dir function in Javascript?
I was looking for a javascript function equivalent to the function dir python. In Python, if I want to see all methods associated with a given object, just pass the function dir directly to…
-
3
votes3
answers117
viewsQ: How to identify output status in a bash program?
I have a bash that runs a series of scripts in other languages. When I step from one script to another I use the first form of conditional (&&) which I understand as "run the next script if…
-
2
votes1
answer97
viewsQ: What is the bash equivalent of python’s sys.argv method?
In python, when I want to use a user-given string in the command line, I use the method sys.argv. For example, let’s say I have an executable called 2name.py consisting of the following code: import…
-
2
votes1
answer39
viewsA: How do I access an attribute(which is a list) of a class by a method outside that class in python?
Well, if you define the method within the class, which seems more natural to me, just do: self.produtos Within the class definition, whenever you want to call a hypothetical instance of the class…
-
2
votes1
answer467
viewsA: Turn row into column
A possible solution is to open the file again and select only the information you want. With this information, you create a new column. Since you didn’t present a replicable example, I created a…
-
1
votes1
answer202
viewsQ: How to use the negation operator in regular expressions for a specific string?
Studying the negation operator in regular expression ([^]) regular, I understood that it is possible to deny an isolated character (e. g., [^x]: anything other than "x") or a range of characters…
-
3
votes2
answers413
viewsQ: How to copy files from one directory to another using regex?
On the linux terminal, when I want to list files in a directory using regex, I do: #exemplo listando arquivos começando com uma letra maiúscula ls | grep -oP '^[A-Z].+' The flag oP is used for…
-
1
votes1
answer29
viewsA: column insertion via python series
Inserting columns into a dataframe can be done in two ways. Creating new columns: df = pd.DataFrame() serie = 'F G H I J'.split(' ') for s in serie: df[s] = [] print(df) Merging from another bank:…
-
1
votes1
answer56
viewsA: Collect fraction of a text in a Pandas column [Python]
What you need is a regex of the kind: '(#*[A-Z][a-z]*[\s-]*[A-Z]*[a-z]*)+\shttps' Using it within a function: def get_country(k): try: result =…