Posts by jfaccioni • 1,283 points
57 posts
-
2
votes2
answers48
viewsA: Return rows from a dataframe that are not in another dataframe
You can do it this way: producao.loc[~producao['Id'].isin(base_dados['Id'])].reset_index(drop=True) output from the above code: Id Fruta 0 06 Melancia 1 07 Melao In short: the expression…
-
1
votes1
answer30
viewsA: How to unify dates with Python dataframe
Starting from the following dataset as an example: df = pd.DataFrame({ 'Nome': ['João', 'José'], 'Sobrenome': ['Da Silva', 'Soares'], '2011-02': [10, 20], '2009-08': [90, 200], '2011-12': [1, 5], })…
-
2
votes1
answer34
viewsA: Create Moving Average column for various assets (python - finance)
I will suggest a slightly different approach; instead of starting from a dataframe where each column represents a company, let’s work with a dataframe where each column represents a attribute of…
-
4
votes1
answer42
viewsA: Create a column filled with 0 or 1 based on other columns in Pandas
First establish the columns you want to use to check the condition: # definindo colunas manualmente cols = ['Col_0', 'Col_1', 'Col_2', ...] # preencha com as colunas aqui # ou então usando uma…
-
1
votes1
answer23
viewsA: How to create a python executable program and publish to Pypi
The argument is missing entry_points in his setup.py. This argument defines the "input points" of your package, i.e., indicates which function of your package you wish to associate with a command…
-
1
votes1
answer29
viewsA: Pandas group into groups with a determining range
First create a column with the age range (can be using the pd.cut as you tried), then group through it: df = ... # seu DataFrame aqui faixas_etarias = np.arange(0, df['idade'].max()+1, 20)…
-
0
votes2
answers34
viewsA: How to access an attribute or method from a variable?
You can take a method / attribute any of an object through a string with the function built-in getattr: import numpy as np a = np.array([1, 2, 3]) # a linha abaixo equivale a escrever "soma =…
-
0
votes1
answer33
viewsA: How to create bar graph with 2 different y axes and the same x axis?
Generally speaking, it is easier to use objects Axes module matplotlib.pyplot directly than trying to plot with df.plot (that nothing else is a "shortcut" that pandas offers to try to plot things…
-
2
votes1
answer23
viewsA: Force the user to answer a valid alternative in a multiple choice Python question system
Use a little bow while that continually asks for user input until it enters one of the possible alternatives: resposta_usuario = input('Sua resposta: ') while resposta_usuario not in ('a', 'b',…
-
3
votes3
answers74
viewsA: Picking numbers from a string - python
The regex you seek is [0-9]+ which matches the parts of the string it contains at least one or more digits: import re entrada = "<SCANNER A7891203021106>, <SCANNER A7891203021106>,…
-
1
votes2
answers67
viewsA: Does every function need a Return at the end of its execution?
The answer depends somewhat on what you mean by "needing a return". If you’re asking if Python always returns some value of a function, the answer is yes. All Python functions return some value,…
-
0
votes1
answer51
viewsA: Pyqt5 - Inheriting information from one class to another. (Python)
If what you want is a secondary window that opens, takes a value and returns it to the main window, you can make your secondary window inherit from a QDialog. This class has a method called exec_…
-
1
votes1
answer40
viewsA: How to change colors in graphics using matplotlib
First, if you want to plot a dot/scatter chart (scatter Plot), use the function plt.scatter. In this type of graph, what you need is a sequence indicating the corresponding color of each plotted…
-
1
votes1
answer27
viewsA: How to use PIL floodfill in python?
Remember the function of the "bucket" of Paint? The floodfill works similarly: you pass a color and an XY point, and the PIL tries to "fill" the region around the XY point with the desired color. Of…
-
1
votes2
answers91
viewsA: How do iterators created from lists rescue "random" values in Python?
You seem to be getting a little confused when talking about generators and iterators. Are you right to say that generators generate their values dynamically, that is, if we have the generating…
-
3
votes2
answers202
viewsA: How to prevent a class from being instantiated in Python?
If I understand correctly, what you are looking for is to define the functionality of the method __init__ (or any other method) in the class Mother, but wants only the class Daughter can actually be…
-
0
votes1
answer48
viewsA: Turn a column into several other columns into a pandas data frame
First add a column with a constant value, then use pivot_table (we need the column with constant value because to pivot we need a column with the values to be filled in the resulting table).…
-
0
votes1
answer43
viewsA: Set a runtime variable from a string and a python object
If I understand correctly, you want enter a variable using a string that contains the variable name. If the variable is global, you can use the function globals, which returns a dictionary…
-
0
votes1
answer50
viewsA: How to resolve Qobject::connect: Cannot Queue Arguments of type 'Qvector<int>' error in Pyqt5 using threading to update Gui interface
I don’t know exactly what the nature of the error you see, but I believe it is because of some incompatibility between the Qt and Python threading system. Ideally, when using Pyqt, you use the…
-
2
votes2
answers88
viewsA: Intersection of words with Python dictionaries
The easiest way is by using a Python dictionary where each of your keys represents a word, and its value is an associate list of text numbers where a given word appears. Using sets would also be…
-
2
votes1
answer161
viewsA: Add different scales in matplotlib
This is a data visualization problem. Your proposed solution would be to "break" the Y-axis at different times, but in my opinion, it simply causes you to lose information - what is the point of…
-
2
votes1
answer56
views -
3
votes3
answers190
viewsA: How to get the index of the first positive element in a list?
If instead of the list we are working with a 1D arrangement of the numpy, we can do it this way: import numpy as np def index_of_first_positive_element(array: np.ndarray): bool_array = array >= 0…
-
2
votes1
answer69
viewsA: Create multiple Dataframes through iteration
It seems to me that you are looking for a dictionary, for example: d = { n: pd.DataFrame({ "A": [random.random(), random.random()] }) for n in range(10) } It is now possible to access each Dataframe…
-
3
votes3
answers351
viewsA: How to access the key, by value, in python dictionary?
Here is another solution that deals with the situation where there are two people of maximum height in the dictionary: pessoas = { "João": 1.71, "Maria": 1.69, "Alberto": 1.75, "Joana": 1.70,…
-
2
votes1
answer62
viewsA: How does this piece of code work?
The expression of the type (func(e) for e in seq) is called generator expression (or Generator Expression in English). It is used to create a sequence by taking the elements of another sequence and…
-
0
votes2
answers65
viewsA: How to use the filter function using lists?
Use filter and lambda will be more complicated than necessary here. I recommend using a list comprehension, which is more readable, together with the function enumerate, iterates on the elements of…
-
0
votes1
answer57
viewsA: How to sort a list through an object attribute?
Use the function sorted and enter a value for the argument key. This value will explain to the function sorted the logic to be applied when sorting the elements. One widely used way is to use an…
-
0
votes1
answer23
viewsA: How can I compare a variable within a list of lists by reading/changing their content in Python?
Are you confusing the one-line index with the element (list) one-line. In your loop: for row in board: for column in row: if p_move == board[row][column]: board is a list of lists, so when iterating…
-
2
votes2
answers69
viewsA: Make sure the entry doesn’t happen again, numerically and within a range?
It is always best to divide a large or multi-step task into smaller tasks. Look at this code structure that uses functions to do the tasks you have established: def casa_eh_numero_valido(casa):…
-
0
votes3
answers723
viewsA: Python: conditional sum with variable condition
You need to use pandas.groupby to group by company, and then cumsum to make the cumulative sum for each group (enterprise). Knowing this is a matter of a line: df = pd.DataFrame({ "empresa":["HST",…
-
1
votes1
answer322
viewsA: Attributeerror: 'list' Object has no attribute 'distance'
In the first iteration of your loop while(b.getDistancia() > 0):, you call: abertos.sort(key=lambda x : x.distancia) that is, you order your list abertos by parameter distancia of each item in…
-
1
votes4
answers169
viewsA: Python - Return all cities of a.txt file in a percentage range
Try to parse symbols in a string like "<" or "%" is, in my opinion, more work than it is worth. The more you manage to limit user input, the better. It is simpler to warn the user that the first…
-
0
votes1
answer76
views -
0
votes2
answers118
viewsA: Python move files to sub-folders of single name
There are some problems with your code: you create the variable files_a, a string list, once. Since the list size never changes during your code, the condition while len(files_a) >= 8: will…
-
4
votes1
answer41
viewsA: Doubt about "resorteio" of equal values
It would even be possible to ask the code to repeat the draws of all players, or only of the players with the same number, but consider the following approach instead: start a numerical sequence…
-
0
votes1
answer165
viewsA: X-axis positioning using Matplotlib in python 3.x
I don’t know exactly what you mean by "I need the x-axis to be at the point(0.0)". If you’re talking about show XY source axes, you can do it using axvline and axhline to plot a vertical and…
-
0
votes1
answer551
viewsA: How to place the value for the y-axis next to the chart marker?
Use the method ax.text passing to it the XY position of the text and the text to be displayed, for example: import matplotlib.pyplot as plt xs = range(10) ys = [x**2 for x in xs] fig, ax =…
-
0
votes1
answer24
viewsA: plotting plineplot with Seaborn excluding certain elements
Simply remove the lines from the state of São Paulo before plotting: dados_sem_sp = dados.loc[dados['state'] != 'São Paulo'] ax = sns.lineplot(x=dados_sem_sp['date'], y=dados_sem_sp['cases'],…
-
1
votes1
answer912
viewsA: Set bar space using matplotlib
This happens because the method ax.bar is crowding bars into X-axis positions that are smaller than the width (variable width) of each bar. For example, the first points of the series you plot when…
-
2
votes1
answer2767
viewsA: Valueerror: Input contains Nan, Infinity or a value Too large for dtype('float64') ( I did the check and none of these proceed)
Without access to the data I can’t test to see if this is it, but note that the lines data.drop(['budget'],axis = 1) data.dropna() are not operations in-place. So much Dataframe.drop how much…
-
3
votes1
answer48
viewsA: Pyhton move files according to quantity
files.count(9) counts how many times the int 9 appears in the list files. As he does not appear any time (files is a list of strings), returns 0. A conditional in form if alguma_expressao and 0 will…
-
0
votes1
answer158
viewsA: How can I view an Axessubplot object in the same way as pyplot.show()?
Every object Axes has an object Figure which contains it (starting from the principle that it was initialized correctly). A Figure may contain multiple Axes, in the case of a figure with more than…
-
1
votes1
answer421
viewsA: Problem in performing a Groupby of a Dataframe - Pandas
Remove the argument axis=1 of your code. Example: import pandas as pd >>> df = pd.DataFrame({ ... 'cases': [2, 3, 4, 2, 4], ... 'state': ['MG', 'MG', 'SC','RS', 'SC'] ... }) >>>…
-
3
votes1
answer42
viewsA: How to handle an error within any Python class?
If you want to deal with one AttributeError raised by whichever access to an attribute not in its class, implement the special method __getattr__: class Foo(object): def __getattr__(self, attr):…
-
2
votes2
answers658
viewsA: Check if the values of a certain Dataframe column exist in a certain list using np.Where
I know you asked to use np.where, but here’s a solution that uses a slightly more readable syntax, in my opinion: df['Sulamericano'] = df['Pais'].isin(america_do_sul).astype(int)…
-
3
votes1
answer108
viewsA: For nested only works in first iteration (Python)
The function open returns a file object. When we read the contents of this object, or iterate over it line by line as you do in your code, we arrive at the "end" of the file. At this point, any…
-
0
votes1
answer280
viewsA: Search object by PYTHON class attribute
This search is certainly feasible, but there is no "ready" Python implementation to do it. Python has no way of knowing a priori of the existence of the class Pessoa, or that each instance has an…
-
1
votes2
answers770
viewsA: PYTHON - Typeerror: 'numpy.float64' Object is not iterable
You are overwriting your variable p (the initial array) when calling each element inside it as p also. That way, on the line for q in p:, p is no longer your initial array, but one of its elements.…
-
0
votes2
answers160
viewsA: Comparison between Dictionary and List
usuarios is a list of dictionaries, and not a dictionary. Therefore, the syntax usuarios['nome'] will fail. To get user names, you will need to iterate on this list and collect the value associated…