input_text_instruct
stringlengths
282
37.9k
output_text
stringlengths
37
27.3k
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to use an optimization algorithm to find the best possible parameter<p>I'm trying to find a good interval of colors for color masking in order to extract skin...
<p>I would suggest using genetic optimization which can be easily implemented for as simple problem as yours. Since the problem is relatively &quot;small&quot; it should not take much longer to find optimal solution compared to some local optimization method like Hillclimb suggested by @Leander. Genetic algorithm is a ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Matplotlib isn't plotting my numpy array if the first value is np.nan<p>I'm trying to make a type of box plot by using this code</p> <pre><code>import numpy as np...
<p>You can mask the <code>NaN</code> values using numpy's <code>isfinite()</code> function.</p> <p><strong>Example:</strong></p> <pre><code>import numpy as np import matplotlib.pyplot as plt N = 3 ind = np.arange(N) # the x locations for the groups width = 2 # the height of the bars: can also be len(x) sequen...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Assign Values from a Header within Dataframe to All Rows in Dataframe by Index<p>I have a large dataset I am working through with Pandas that is pulled from Excel...
<p>Use <code>ffill</code> (or <code>fillna(method='ffill')</code>):</p> <pre><code>df['UnitNo._new_col'] = df['UnitNo.'].ffill() print(df) # Output: Date/Time UnitNo. Reading UnitNo._new_col 0 NaN UnitBc36 NaN UnitBc36 1 1/1/2021 NaN 100.0 UnitBc36 2 1/1/2...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Value "not a number" in my dataframe not found<p>I have a problem because I can't find the NaN values that appear when I use describe() on my dataframe. I'm worki...
<p>As you confirmed, it seems that there is no NaN in <code>df</code>.</p> <p>I think you are confused with what <code>df.describes</code> returns. <code>df.describes</code> returns a summary of the dataframe. <code>df</code> is not <code>df.describe()</code>.</p> <p>When you use <code>describe()</code>, the <code>NaN<...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Splitting dataframe into multiple ones according to proportion of samplesize and labels<p>I want to create my training, validation and testset from one dataframe ...
<p>When you have an imbalanced dataset, you can use the parameter <code>'stratify'</code> in the <code>train_test_split()</code>. This will make the dataset be split into training and test sets in such a way that the ratio of the class labels in the variable specified is constant i.e. both train and test set will have ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Using * with plotting - matplotlib<p>I am trying to understand how unpacking could work with matplotlib in regards to condensing and simplifying code. Say:</p> <p...
<p>I'm not sure what you intend by &quot;I wanted to plot four points at each of these coordinates&quot; (what's the point of 4 overlapping points?), but...</p> <hr /> <p>Let's transpose first:</p> <pre><code>ax.plot(*P.T, marker='o', ls='None') </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/fHBhE.p...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how to make json.loads() read a json string with the column names as the first element<p>I am serializing a datatable from a http get and for performance reasons ...
<p>I did some digging and found ijson. It lets you iterate over a json file and access its objects. you can build you data structur like this(i was lazy and used pd):</p> <pre><code>import ijson import pandas as pd f= open("testjson.txt",'r') f2= open("testjson.txt",'r') names=[] values=[] names = ijson.items(f, 'Name...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to display multiple images at once with matplotlib in one figure?<p>I want to display multiple images at once in one figure (i used a set of 22 images so fo...
<p>The problem is you are displaying the plot within the loop, and should display it after you have placed all the images.</p> <p>Move <code>plt.show()</code> outside the loop.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how to draw by mouse an interactive fixed grid within a gui or figure? /python / matplotlib / pyqt5<p>The below code allows me to draw an interactive rectangle an...
<p>If I understood it correctly, m and n are constants. If not, you can set them high enough. Matplotlib is designed for plotting functions, so PyQt5 is probably a much better choice (especially if you extend the functionality further).</p> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.Q...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Why using a time-based pseudo-random number is not cryptographically secure?<p>It is well known that pseudo-random numbers are not cryptographically secure.</p> <...
<p>For cryptography, it is not only desirable that <em>individual</em> numbers are hard to predict but also that <em>multiple</em> numbers are hard to predict – that is, numbers should (appear to) be independent.<br /> Notably, they should be independent even if an attacker knows the algorithm.</p> <p>That is problemat...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Can I do 'screenshot' of image on the Python Tkinter Canvas and save it in the file?<p>I made program to make images in Python tkinter Canvas, but I have no idea ...
<p>Since there is no code provided, I will give you an example on how this is done. By default there is no methods within tkinter that does this for you. So for taking screenshots, we will use <code>PIL</code>.</p> <ul> <li>Start by installing <code>PIL</code>:</li> </ul> <pre><code>pip install Pillow </code></pre> <ul...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Calculating daily difference for 15 minutes data in pandas<p>I have a huge dataframe of open and close prices recorded every 15 minutes of the day. The day starts...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.last.html" rel="nofollow noreferrer"><cod...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How Can I Detect If There are Secondary Objects in an Image<p>I am looking for a way to detect if there are secondary objects in an image or if the image just has...
<p>Here is one way to do that in Python/OpenCV</p> <ul> <li>Read the input</li> <li>Convert to gray and invert</li> <li>OTSU threshold</li> <li>Morphology close</li> <li>Get external contours</li> <li>Draw contours on image</li> <li>Count contours</li> <li>Print messages</li> <li>Save results</li> </ul> <p>Input:</p>...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: pandas - Summing over rows with strings collapses my dataframe<p>I want to match information in rows for different group and thought a summation would work well.<...
<p>If <code>nan</code>s are missing values or strings is possible first replace it by empty strings and then use <code>join</code>:</p> <pre><code>df = df.replace('nan', np.nan).fillna('').groupby('name').agg(''.join) print (df) t1 t2 name A offoff onon B onon off C offoff o...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: create a list filled with elements, length depends on given number<p>say I have a function which takes in a number e.g def function(number), I want to create a li...
<p>You can do it in a few different ways.</p> <p>Best way:</p> <pre class="lang-py prettyprint-override"><code>number = 2 list1 = [None]*number </code></pre> <p>For Loop:</p> <pre class="lang-py prettyprint-override"><code>number = 2 list1 = [] for _ in range(number): list1.append(None) </code></pre> <p>List Compre...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Find out if there is nesting of comments in C file using python script<p>This is a code to find out if there is nesting of comment in a sample.c file but I am get...
<p>In <a href="https://docs.python.org/2/library/re.html" rel="nofollow noreferrer">Python regular expression</a> (RE) syntax, <code>*</code> is a <em>special character</em> indicating a match of 0 or more repeats of the previous RE. The pattern, <code>'*/'</code> is saying "repeat nothing" because there is "nothing to...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Creating a list from a text file<p>I have a text file called <code>my_urls.txt</code> that has 3 URLs:</p> <pre><code>example1.com example2.com example3.com </cod...
<p>You need to iterate over the open file. This iterates over the lines for you:</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;../test_data/my_urls.txt&quot;, &quot;r&quot;) as urlFile: urls_list = [] for url in urlFile: urls_list.append(url.strip()) print(urls_list) </code></p...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Ignore all warnings from a module<p>i'm having some problems with librosa python module. It shows me the following warning at import. </p> <pre><code>/opt/anacon...
<p>Try:</p> <pre><code>import warnings from numba.errors import NumbaPerformanceWarning warnings.filterwarnings("ignore", category=NumbaPerformanceWarning) </code></pre> <p>If the above doesn't work:</p> <pre><code>import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: python, inserting in to 2d list<p>I am trying to insert &quot;X&quot; to specific place in list. it seems to place &quot;X&quot; in every list. There is parts of ...
<p>You keep appending the same exact <code>b</code> list, the same instance, so when you modifying one, you see it everywhere, you need to copy it</p> <pre><code>stworzona_tablica.append(b) # NOK stworzona_tablica.append(list(b)) # OK </code></pre> <hr /> <p>Also, better practices to</p> <ul> <li><p>don't use g...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: python: parse a colon-separated formatted string<p>I need to write a <code>python</code> script (I'm a newbie in <code>python</code> but would like to take this a...
<p>Create an <code>iterator</code> over your string:</p> <pre><code>message = '1:4:a:5:6:7:2:10:72:75:63:6f:6e:74:72:6f:6c:6c:65:72:2e:6f:72:67' code = iter(message.split(':')) data = {} for t in code: l = int(next(code), 16) d = [next(code) for _ in range(l)] data[t] = d </code></pre> <p>Output:</p> <pre...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Check if user is in a voice channel discord.py<p>I am making a bot that will play sounds in a vc. I have made the code to join the call, play the mp3, then leave ...
<p>You can simply check if it's not a nonetype with an if statement</p> <pre class="lang-py prettyprint-override"><code>@bot.command() async def foo(ctx): voice_state = ctx.member.voice if voice_state is None: # Exiting if the user is not in a voice channel return await ctx.send('You need to be...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to make 2 functions for 2 tkinter windows more condensed?<p><strong>Question:</strong></p> <p>I have 2 similar tkinter windows, which I would like to condense...
<p>I will give you an example where you can use a <em>template</em> and then edit the values, I am using frames, which can be raised when pressed upon different button.</p> <pre><code>from tkinter import * class Form(Frame): def __init__(self,master,user_txt,img,pw_txt,btn_txt,callback,*args,**kwargs): Fra...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pycharm keeps saying Name 'User' can be undefined<p>I was learning Json and Pycharm keeps warning me about <code>Name 'User' can be undefined</code> how do I get ...
<p>Try</p> <pre><code>import json with open(&quot;Users.json&quot;) as f: data = json.load(f) User = None username = input(&quot;Enter Username:&quot;) for users in data: User = users if username == User: print(User) print(&quot;lol&quot;) </code></pre> <p>also, might I suggest adding the if stateme...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: To find if the input given is lucky or not<p>My aim: Two inputs will be given. purchase date and number on plate. My code should add all numbers of purchase date ...
<p>Here is a nicer, simpler and cleaner way to solve your problem:</p> <pre><code>import re def recursive_sum(text): while (len(text) &gt; 1): numbers = re.findall(r'\d', text) _sum = sum(map(int, numbers)) text = str(_sum) return text def luck_dare(): input1= input("enter ; ") ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Convert JSON date list to python date format<p>I've got this list of birthdate that is in JSON format, that I want to convert to Python format. What would be the ...
<p>You can use <code>datetime.fromtimestamp()</code> in <code>datetime</code> module to convert epochtime to datetime, as follows:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime birthdate_json = [ '/Date(1013230800000)/', '/Date(1016600400000)/', '/Date(1010466000000)/', ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Create list from serveral oclumns in pandas dataframe<p>I have the following dataframe:</p> <pre><code>name age year salary1 salary2 salary3 salary4...
<p>Try this:</p> <pre><code>df['new_column'] = df[['salary1', 'salary2', 'salary3', 'salary 4']].values.tolist() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to concatenate arrays based on number of pair formula<p>I have some arrays. Now, I want to concatenate these arrays based on this formula (<code>n*(n-1)/2</co...
<p>You can use <code>itertools</code> and <code>combinations</code>. One simple example is given below if you want to make combinations for 2 lists</p> <p>code</p> <pre><code>from itertools import combinations list(combinations([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], 2)) </code></pre> <p>Output</p> <pre><code>[(...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How do I convert a list into a dictionary grouped by object name?<p>Say I have a list with classes:</p> <pre><code>[Blue((2, 1)), Blue((4, 2)), Orange((3, 2))] </...
<p>Assuming that <code>Blue</code> and <code>Orange</code> are classes, you can find the classname of each object using <code>type()</code> and the <code>__name__</code> attribute. Then, you can collect instances of each class into lists using a <code>collections.defaultdict</code>:</p> <pre class="lang-py prettyprint-...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Manipulating DataFrame<p>I have the following dataframe <code>df</code> where there are 3 columns: Date, value and topic. I want to create a new dataframe <code>d...
<pre><code>df1 = (df.assign().pivot_table(index='Date', columns='Topic', values='Val')) </code></pre> <p>Output</p> <pre><code>Topic 0 1 2 3 4 Date 2015-02-24 00:00:00 ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to filter a Model with a One-To-Many Relationship using Flask-Sqlalchemy?<p>I'm new to Flask-SQL-Alchemy so this may be a noob quesiton. Let's say I have a Tw...
<p>I think you are missing the second part as seen here <a href="https://stackoverflow.com/questions/13640298/sqlalchemy-writing-a-hybrid-method-for-child-count">SQLAlchemy - Writing a hybrid method for child count</a></p> <pre class="lang-py prettyprint-override"><code> from sqlalchemy.sql import select, func class U...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Dynamically import a python file whose name is stored in a variable<p>I have 2 python scripts. First python script name is <code>&quot;test_1.py&quot;</code> and ...
<p>You can use:</p> <pre><code>import importlib module_name = input('Enter a module name you want') dynamically_imported_module = importlib.import_module(module_name) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How can I return what I expect from nested list or dictionary comprehension?<p>I've tried two different approaches to this problem.</p> <p>Here's a nested list co...
<blockquote> <p>What I'm getting instead is a list of tuples with each tuple containing 1 item with both variables.</p> </blockquote> <p>Not quite -- what you're getting is a list of lists, with each inner list containing the tuples for a single tag. That's because you have two nested list comprehensions (<code>[[]]</...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Unable to select from table starting with "@" in Python fdb<p>I'm using FDB module to fetch data from Firebird database using Python. I'm trying to fetch data fro...
<p>"Regular identifiers" in Firebird SQL server can not contain <code>@</code> symbol, see <a href="https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-structure-identifiers.html" rel="nofollow noreferrer">Identifiers</a>.</p> <p>With SQL Dialect 3 you can have quoted irregular...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Conditional Filtering in Generator with random integer<p>I would like to create a generator of random numbers.</p> <pre><code>import numpy as np rd_list = (np.ra...
<p>Another way using assignment expression (Python 3.8+):</p> <pre><code>import random nums = (n for _ in range(6) if (n := random.randint(0, 10)) &lt; 5) </code></pre> <p>Thanks to Andrej's comment: Since you are already using <code>numpy</code>, you don't need the loop:</p> <pre><code>import numpy as np nums = (n f...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to drawtext with a color gradient fill with ffmpeg (ffmpeg-python)? and then mix with music?<p>I'd like to achieve this result (to place a text with gradint o...
<p>We may draw the text on black background, and use <code>alphamerge</code> for creating transparent background with colored gradient text.<br /> Then we can overlay the gradient (with the transparent background) on the input video.</p> <p>I don't know if my suggested solution is the most elegant, but it is not lower ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Finding minimum values on a 1min data<p>I have a timeseries data in the following format:</p> <pre><code>| quote_datetime | Moneyness | underlying_bid | askC | a...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>.transform</code></a> after grouping if you want your dataframe to stay in the same shape:</p> <pre class="lang-py prettyprint-override"><code>df['fwd_premium_abs'] = df.groupby('quote_d...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Convert to Racket(Scheme)<p>I have this code that works, on python. I am new to DRrACKET, how can I translate it into DRrACKET. I am struggling to write a DRrACKE...
<p>Attempting to &quot;translate&quot; from Python is probably not the best approach when learning Scheme/Racket; try starting with this <em>stub</em>, and following the Racket <a href="https://courses.edx.org/courses/course-v1:UBCx+HtC1x+2T2017/77860a93562d40bda45e452ea064998b/#HtDF" rel="nofollow noreferrer">How To D...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Center OK button in QDialog<p>Is it possible to center the OK button in a QDialog?</p> <pre><code>class CustomDialog(QDialog): def __init__(self, text, parent...
<p>The simplest way is to use the <a href="https://doc.qt.io/qt-5/qdialogbuttonbox.html#centerButtons-prop" rel="nofollow noreferrer"><code>centerButtons</code></a> property:</p> <pre><code> self.buttonBox.setCenterButtons(True) </code></pre> <p>Also consider that by default widgets are added to a layout by trying t...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Print dict in Django Template<p>I have a dict defined like that:</p> <pre><code>table_data = [{'aircraft': &lt;Aircraft: P28A I-ASTV&gt;, 'row_data': [{'colspan':...
<p><code>row_data</code> is a <em>list</em> of dictionaries, so you access this with:</p> <pre><code>{% for data in row.row_data %} &lt;td colspan=&quot;{{ data<strong>.colspan</strong> }}&quot;&gt;{{ data<strong>.booking_obj</strong> }}&lt;/td&gt; {% endfor %}</code></pre> <p>Here <code>data</code> is thus a dicti...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Image compare or classification using Python<p>I am really not sure if I am looking for image classification or its called something, please help me understand my...
<p>I suggest to go with PIL or openCV python libraries which will handle all image processing functionalities .</p> <p>PIL - <a href="https://pillow.readthedocs.io/en/stable/" rel="nofollow noreferrer">https://pillow.readthedocs.io/en/stable/</a></p> <p>openCV - <a href="https://docs.opencv.org/master/" rel="nofollow n...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: python - ldap3 lib: How to add multiple values to attribute<p>I want to add more than one email adress to a user in ldap. Therefore is an attribut called mailLoca...
<p>I'm not able to reproduce the behavior you've reported. If I start with this in my ldap directory:</p> <pre><code>dn: dc=example,dc=com objectclass: dcObject objectclass: organization o: example dc: example dn: ou=people,dc=example,dc=com objectclass: organizationalunit ou: people </code></pre> <p>And then run the...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Create columns from row values and fill - pandas<p>I have a dataframe that looks like this:</p> <p><code>df=pd.read_csv('https://raw.githubusercontent.com/amanaro...
<p>I think <code>pivot()</code> is the right function for your problem. It takes the categorial values of <code>Video_Category_Name</code> and creates new columns, which are filled with the value of <code>score_pct</code>. Non existing values are replaced by zero with `filna(0):</p> <pre><code>df = df.pivot(index='Chan...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Why has pip3 install multiprocessing failed in Windows subsystem for Linux?<p>I'm relatively new to Linux, and I need to install Python's multiprocessing library ...
<p>Python 3 has the <code>multiprocessing</code> module built in. You do not need to install it from pip. You can just <code>import multiprocessing</code> and use it.</p> <p>What happens here is that pip tries to install the Python 2 version, because back then, <code>multiprocessing</code> was a third-party package.</p...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Is there a dummy Scaler that does nothing to plug into a Pipeline?<p>Is there a dummy Scaler to plug into a Pipeline that does nothing? i.e.</p> <pre><code># def...
<p>Actually using <code>None</code> works perfectly as "do nothing" i.e. </p> <pre><code>params = [{'preprocess': [None, MaxAbsScaler(), MinMaxScaler(), StandardScaler()], 'model__gamma': ['scale', 'auto'], 'model__C': [1.0, 1.01, 1.015,3.0] }] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to efficiently scatter plot a numpy 2d array<p>I have a numpy with each row containing x, y pairs and I want to display a scatter plot without using a for loo...
<p>If I understood correctly, you want to slice your numpy array:</p> <pre><code>x = centroids[:, 0] y = centroids[:, 1] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to take requested data as json object in django views?<p>I'm submitting my form from postman. But i'm getting all key values as a list. I don't know why, how ...
<p>You can write simple loop over it,</p> <pre><code>response = {'from_email': ['a@gmail.com'], 'to_email': ['b@gmail.com'], 'subject': ['hey man whats up ?'], 'html_body': ['seom']} dummy = dict() for key, val in response.items(): dummy[key] = val[0] print(dummy) {'from_email': 'a@gmail.com', 'to_email': 'b@gm...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How can I apply a limit on input(not more than 20 letters) and the input value can be just alphabet?<pre><code>def save_load_page(): bg = pygame.image.load(re...
<p>You have to evaluate if the length of the text is less than 20, before you add the new character. <a href="https://docs.python.org/3.8/library/stdtypes.html#str.isalpha" rel="nofollow noreferrer"><code>isalpha()</code></a> can be used to test whether a character is a letter (see <a href="https://stackoverflow.com/q...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas new col with indexes of rows sharing a code in another col<p>Let say I've a DataFrame indexed on unique Code. Each entry may herit from another (unique) en...
<p>You can group by the <code>Herit</code> column and then reduce the corresponding <code>Code</code>s into lists:</p> <pre><code>&gt;&gt;&gt; herits = df.groupby(&quot;Herit&quot;).Code.agg(list) &gt;&gt;&gt; herits Herit [a, b, c] a [aa, ab] b [ba] </code></pre> <p>Then you can <code>map</code> the ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to maintain the order of heatmap sorted by column A in a heat plot of column B<p>My <code>dataframe</code> consists of trajectories split into segments. Other...
<p>Put <em>both</em> <code>actual</code> and <code>prediction</code> values in the pivot table and then plot either column group or both of them side by side. For this it's best to split data processing and plotting into two separate functions.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import m...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Why I am having an error on send_keys using selenium python<p>I'm trying to make a script that logs me into my account automatically and I'm stuck at <code>send_k...
<p>Generally different sites follow different design approaches, which doesn't allow normal script flow &amp; needs additional steps to be added.</p> <p>In you case, the default CSS style blocks your input. So, first click on that element( Which makes it as focused) then send your keys.</p> <p>Element Attribute diffe...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how to shows options when create class and inheritance from Gtk.ComboBox<p>I made class named <code>Combo</code> and inheritance from <code>Gtk.ComboBox</code> in...
<blockquote> <p><strong>Question</strong>: <code>class inheritance</code> from <code>Gtk.ComboBox</code></p> </blockquote> <p>First, i want to show what is wrong with your implementation.</p> <pre><code>class Combo(Gtk.ComboBox): def __init__(self,opt): </code></pre> <ol> <li>Here you <code>__init__</code> th...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to modulate the size of the nodes of a network analysis with a certain value for each edge?<p>in the current graph the size of the nodes is given by the &quot...
<p>Below I show, how to calculate the sum of edge weights of outgoing edges and scale the nodes accordingly:</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({ 'weight':['50'] * 4 + ['500'] * 5 + ['20'] * 3 + ['100'], 'node a':['pippo', 'pippo', 'pippo'...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python Selenium window closing no matter what<p>I don't really like to ask questions but I just can't find out what is wrong with my code. I'm new to selenium so ...
<p>After your test case finishes running, it will close the browser no matter what. In your case browser will be closed as soon as you navigate to youtube. You don't have anything else and your test case is finished as soon as you navigate to youtube.</p> <p>But, if you would like to observe more and stay on youtube on...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Embedding multiple real-time graphs in one Python Tkinter GUI<p>I am new with Tkinter. I am trying to plot two real-time animated graphs in a window, but two real...
<p>If You don't specifically need canvas1 and 2, You can create two subplots for one figure / canvas.<br /> Then You will get 2 axes: <code>ax1</code> and <code>ax2</code>.</p> <p>You can use just one <code>FuncAnimation</code> with same <code>x</code>. If You need separate animations for <code>ax1</code> and <code>ax2...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Unclose a nested dictionary to simple dictionary without using recursion<p>Below is a dictionary which has keys as string and value as either a dictionary or inte...
<p>You need to traverse your dictionary. Though this will use <code>recursion</code>.</p> <pre><code>def traverse(dictEx): for k, v in dictEx.items(): if isinstance(v, dict): traverse(v) elif type(v) == int: print({k:v}) sample = {&quot;A&quot;: 1, &quot;B1&quot;: {&quot;BB1&...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Get unique list of strings by string substring<p>I made this working code but maybe it's possible to make it shorter?</p> <pre><code>sents_str = 'dimplegalla:2808...
<p>Yes:</p> <pre><code>list({sub for sub in sents_str.split()}) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Get a row of data and display in table using pickle load?<p>I'm new to Python and just learning. I've used pickle dump to store a class object to a text file usin...
<p>I tried my best to answer you. <code>The code</code>:</p> <pre class="lang-py prettyprint-override"><code>import pickle import os.path class LotteryDraw(): def __init__(self,date,ball_1,ball_2,ball_3,ball_4,ball_5,ball_6,bonus_ball): self.date = date self.ball_1 = ball_1 self.ball_2 = b...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to remove/skip <class 'NoneType'> object in Python<p>I am receiving the data from SOAP API call from a vendor and using Zeep library. The data is <code>class ...
<p><code>clean_response_list = [x for x in response_list if x != None]</code></p> <p>This doesn't work because response_list is None, so you can't iterate over it.</p> <p>Try:</p> <pre><code>response_list = response_list or [] </code></pre> <p>Or</p> <pre><code>if response_list is None: response_list = [] </co...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Groupby dataframe to get not null elements from each group member<p>I have a dataframe where in some cases a case has its records in more than one row, with nulls...
<p>You can also use <code>groupby</code> and <code>first</code>:</p> <pre><code>df.groupby("date_rounded").first() 1 2 3 4 5 date_rounded 2020-04-01 00:05:00 0.0 1.0 44.0 44.0 46.454 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to remove all chars from an array, leaving it only numbers?<p>I'm using sklearn.MLPClassifer and i exported my weights into a txt with this:</p> <pre><code>ar...
<p>You can try something like:</p> <pre><code>import os with open('weightss.txt', 'w') as fp: for a in model.coefs_: np.savetxt(fp, a, fmt='%f') fp.write(os.linesep) </code></pre> <p>Demo:</p> <pre><code>rng = np.random.default_rng(2022) coefs = [np.array(rng.random((4, 5))), np.array(rng.random((5...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: What happened when I used pandas to read csv files for multiple time in kaggle's notebook?<p>I am participating the kaggle's <a href="https://www.kaggle.com/c/mar...
<p>I finally found the problem. I didn't notice I was writing my codes in the markdown cell. Stupid me!</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Iterating through list elements and apply to class<p>I'm looking to establish a list, (<code>list_=[a,b,c]</code>), iterate over the list and apply it to a class ...
<p>Attributes are typically accessed from a class using a <code>dot</code> notation, ex: <code>my_class.attribute_1</code>. This is useful when accessing attributes are hard coded.</p> <p>But as you point out, this is not useful when needing to dynamically access attributes, as in the case of the list above. The soluti...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: create robot framework Test Case dynamically on running test suite<p>I got a very specific scenario, where I'm inserting some data to the database(e.g. let's say ...
<p>There is a blog post with a answer for you: <a href="https://gerg.dev/2018/09/dynamically-create-test-cases-with-robot-framework/" rel="nofollow noreferrer">https://gerg.dev/2018/09/dynamically-create-test-cases-with-robot-framework/</a></p> <p>As you suggested the solution is to create a listener so you can add tes...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to create a calculated new column in pandas<p>I'm trying to do something in Python that I can do easily in Excel, but it's simply not working out. Essentially...
<p>without your code its impossible to tell ... but based on the error you described i would expect this to solve your issue</p> <p>you cannot do <code>if dataframe</code> </p> <p>you can do <code>if dataframe is None:</code> if you want to test if its none</p> <p>or <code>if len(dataframe) == 0:</code> if you want ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: replace one floor of a 3D np array by a 2D numpy array<p>I'm trying to &quot;replace one floor of a 3D np array by a 2D numpy array&quot;</p> <p>this is my code, ...
<p>Are you sure your output is correct?</p> <p>I think you meant to do:</p> <pre><code>board_3D[1] = board_2D </code></pre> <p>output:</p> <pre><code>array([[[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9]], [[ 2, 1], [ 2, 4], [ 4, 1], [ 4, 1], ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python - Issue with for loop (lists)<p>I have the following code which prompts the user for a username, then checks if that username exists in a json file, if so ...
<p>Guys thanks for your support, just wanted to say I solved the issue. Basically the challenge was:</p> <ul> <li>I have a list of users in a json format or in a dictionary, in the end it doesn't matter.</li> <li>I prompt the user to enter basic information and then I will append the information to the json file if th...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Use torch.gather to select images from tensor<p>I have a tensor of images of size <code>(3600, 32, 32, 3)</code> and I have a multi hot tensor [0, 1, 1, 0, ...] o...
<p>When using <a href="https://pytorch.org/docs/stable/generated/torch.gather.html" rel="nofollow noreferrer">torch.gather</a>, the dimension of input and dimension of index must be the same. And the index is not a multi hot tensor, but the location of the desired value.</p> <p>You can slice the tensor by using the ind...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to iterate two or more columns and perform analysis in pandas?<p>I have two dataframes, where one dataframe has 2 columns with 11 rows and another dataframe w...
<p>You can accomplish this without for loops taking advantage of elementwise subtraction the following way:</p> <pre><code>import pandas as pd #Example data df = pd.DataFrame({'C1': [i for i in range(1, 12)], 'C2': [i for i in range(2, 13)]}) #Example mean and standard deviation df1 = pd.DataFrame({'Mean': [2, 1], 'De...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to delete focused row in tkinter python?<p>I like to make a button deleting a speficied row using tkinter.</p> <p>I have been trying this problem for a day.</...
<p>You can use <code>self.listBox.curselection()</code> to get a tuple of the line(s) selected and use <code>self.listBox.delete(tuple)</code> to delete these/(those) lines.</p> <p>Just assert that it's going to delete only one line otherwise change the <code>self.num_row -= 1</code></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: ValueError: None values not supported. Code working properly on CPU/GPU but not on TPU<p>I am trying to train a <code>seq2seq</code> model for language translatio...
<p>As stated in the referenced answer in the link you provided, <code>tensorflow.data</code> API works better with TPUs. In order to adapt it in your case, try to use <code>return</code> instead of <code>yield</code> in <code>generate_batch</code> function:</p> <pre><code>def generate_batch(X = X_train, y = y_train, ba...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Django CharField unique argument in new Django version<p>In my forms.py file I am using CharField. I read about unique argument of CharField in the book: it says ...
<p>To validate uniqueness in a form, you could use the forms <a href="https://docs.djangoproject.com/en/3.1/ref/forms/validation/" rel="nofollow noreferrer"><code>clean_fieldname()</code> methods</a> to make an extra DB query before saving the form.</p> <pre><code>from django import forms from django.core.exceptions im...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: calling python function with arguments using tcl script<p>I have a python script (sample.py) that has a function with 3 arguments. where 1st two arguments are in ...
<p>You need to quote it for Python.</p> <p>For an almost-arbitrary value like that, you'd try this:</p> <pre><code>set result [exec python -c &quot;import sample; print sample.print_file($gen_lane,$sw_state,r'''$test_case''')&quot;] </code></pre> <p>This uses the fact that <code>'''</code>-quoted strings in Python can ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Conditional lambda in pandas returns ValueError<p>In a df comprised of the columns <code>asset_id, event_start_date, event_end_date</code>, I wish to add a forth ...
<pre><code>df = pd.DataFrame({ 'asset_id':[0,0,1,1], 'event_start_date':['2019-07-08','2019-07-11','2019-07-15','2019-07-25'], 'event_end_date':['2019-07-08','2019-07-23','2019-07-29','2019-07-25'] }) df['event_end_date'] = pd.to_datetime(df['event_end_date']) df['event_start_date'] = pd....
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python, NLP: How to find all trigrams from text files with adjectives as the middle term<p>I think the question is self-explanatory but here goes the detailed mea...
<p>This code should do it:</p> <pre><code>import nltk from nltk.tokenize import word_tokenize nltk.download('punkt') nltk.download('averaged_perceptron_tagger') text = word_tokenize(&quot;He is a very handsome man. Her childern are funny. She has a lovely voice&quot;) text_tags = nltk.pos_tag(text) results = list() f...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to use DictReader if I use islice from itertool to start at line 5?<p>I have a CSV file with fieldnames that start from line 5.</p> <p>For example,<br> line ...
<p>IIUC, Use:</p> <pre><code>import csv with open('AGM.csv', 'r') as f2: for _ in range(4): next(f2) # skip first four lines # instantiate a dictreader after skipping first four lines reader = csv.DictReader(f2) for line in reader: # start reading from line 5 print(line) </code></pre>...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: ERROR: 'NoneType' object has no attribute 'find_all'<p>I'm doing web scraping of a web page called: CVE Trends</p> <pre><code>import bs4, requests,webbrowser LIN...
<p>This is due to not getting response you exactly want.</p> <p><a href="https://cvetrends.com/" rel="nofollow noreferrer">https://cvetrends.com/</a></p> <p>This website have java-script loaded content,so you will not get data in request.</p> <p>instead of scraping website you will get data from <a href="https://cvetre...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Keep the value corresponding to the maximum of another column in a dataframe<p>I have a DataFrame</p> <pre><code> day type price 0 10900 2 300 1 109...
<pre><code>df[&quot;price&quot;] = df.groupby(&quot;day&quot;, as_index=False)[&quot;price&quot;].transform( lambda x: df.loc[df.loc[x.index, &quot;type&quot;].idxmax(), &quot;price&quot;] ) print(df) </code></pre> <p>Prints:</p> <pre><code> day type price 0 10900 2 200 1 10900 1 200 2 10900 ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Is dict.update() computationally efficient or are there more efficient alternatives?<p>I'm running code which uses 16 processes to build up 16 dictionaries of len...
<p>The time complexity in python is documented <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow noreferrer">here</a>.</p> <p>As @MicahSmith already answered (in the comments) the complexity with updating a dict is O(1) in the average and O(n) in <a href="http://en.wikipedia.org/wiki/Amortized_analysi...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Convert a list of objects to a dictionary of lists<p>I have a list of JSON objects, already sorted (by time let's say). Each JSON object has <code>type</code> and...
<p>I don't know if there is a one-liner but you can make use of <a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" rel="nofollow noreferrer"><code>setdefault</code></a> or <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow noreferrer"><code>defaultd...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: multiple listing index in the loop in python<p>Below is my code which is finding a common element.</p> <p>but I actually want to get the index of it as well, can ...
<p>You can use <code>enumerate()</code> and <code>list.index()</code>.</p> <pre class="lang-py prettyprint-override"><code>for idx, element in enumerate(a1): if element in b1: c.append(element) index_a1.append(idx) index_b1.append(b1.index(element)) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how join 3 table in Django Python<p>This is my first class</p> <pre><code>class dot_bay(models.Model): ma_dot_bay = models.CharField(primary_key=True,max_leng...
<p>The idea here is to use nested serializers. In our case, we'll use those nested serializers to detail how we want foreign key objects to be rendered/structure.</p> <p>Try something like that:</p> <pre class="lang-py prettyprint-override"><code>class NestedHinhAnhModelSerializer(serializers.ModelSerializer): clas...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: When hitting docker: (56) Recv failure: Connection reset by peer<p>My Dockerfile:</p> <pre><code>FROM python:3.8 COPY . /code WORKDIR /code RUN apt-get upda...
<p>I was finally able to get it to work by adding <code>--bind 8000</code> to the docker run command:</p> <pre><code>CMD [&quot;gunicorn&quot;, &quot;--paste&quot;, &quot;development.ini&quot;, &quot;--bind&quot;, &quot;:8000&quot;, &quot;--workers&quot;, &quot;3&quot;, &quot;--reload&quot;] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: What happens if I don't reset Python's ContextVars?<p>Is this a memory leak in Python?</p> <pre><code>import contextvars contextvar = contextvars.ContextVar('exa...
<p>The &quot;token&quot; object object contains the recover-value as a plain attribute of itself (<code>.old_value</code>). Regardless of internal representations, the old values will live for as long as you keep one reference to the token around.</p> <p>Now, if the ContextVar object would stack references to its value...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Rounding down numbers to the next lower .95<p>I want to round a number to the next lower .95:</p> <pre><code>20.84 -&gt; 19.95 31.40 -&gt; 30.95 45.34 _&gt; 44.95...
<p>Since it is easy to round down to the next integer, you can do it like this:</p> <ol> <li>add 0.05</li> <li>round down to the next integer</li> <li>subtract 0.05 again</li> </ol> <p>Step 1 is necessary to avoid converting e.g. 2.98 to 1.95.</p> <p>In Python code:</p> <pre><code>def round_down_95(x): return int(x...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: NameError: name '__file__' is not defined , os.path.dirname(os.path.abspath(__file__))<p>I'm trying to use os.path.dirname(os.path.abspath(<strong>file</strong>))...
<p>There is a good chance that __ file __ is not defined because you execute your code in an interactive shell.</p> <p>Write it in a file and execute it with python and the const __ file __ will be defined.</p> <p>Hope it helps.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: multiplication table python nested loop not printing full table<p>This is my code for my multiplication table so far. I am a bit confused as to how to continue to...
<p>You are replacing the value of <code>x</code> in the loop, instead you should use a different name for looping parameter:</p> <pre><code>output = ' '.join([f" {i}" for i in range(1, x+1)]) + "\n" output += '---' * x + "\n" for i in range(1, x+1): output += str(i) + "| " for y in range(1, x+1): outpu...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to plot a scatter plot on a single y-tick with multiple x-axes using Plotly Python?<p>I'm trying to plot a Scatter plot with a single y-axis and multiple x-ax...
<ul> <li>you can use <strong>ploty express</strong> to generate sub-plots for each of the days</li> <li>have used <strong>pandas</strong> categorical functionality to get sort order correct first</li> <li>figure created by <strong>plotly express</strong> requires touch ups <ul> <li>remove annotations</li> <li>only part...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: What is the difference between the two different ways of importing Python widgets?<pre><code>from PyQt5 import QtWidgets </code></pre> <p>and:</p> <pre><code>from...
<p>RealPython has a real nice explanation <a href="https://realpython.com/python-modules-packages/#the-import-statement" rel="nofollow noreferrer">here</a>, but to summarize <code>from PyQt5.QtWidgets import *</code> isn't considered good practice in a large-scale production, as you are importing everything, which coul...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to use data from csv file in python<p>I'm pretty new to Python and I'm trying to read this data from a csv file (now it is not comma separated, but if it is a...
<p>Use pandas:</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;Data.csv&quot;, sep='\t') df.to_dict() </code></pre> <p>Note: in parameter <code>sep</code> you can use others like <code>'|'</code> - <code>' '</code> - <code>';'</code> ...</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how to scraping multiple image tag under div tag<p>i want to scraping multiple image under <code>div</code> tag but getting error</p> <pre><code>AttributeError: R...
<p>Try this code to extract all image's <code>src=...</code>:</p> <pre><code>from bs4 import BeautifulSoup txt = '''&lt;div class=&quot;class_name&quot;&gt; &lt;img src=&quot;#1&quot;&gt; &lt;img src=&quot;#2&quot;&gt; &lt;img src=&quot;#3&quot;&gt; &lt;img src=&quot;#4&quot;&gt; &lt;/div&gt;''' soup = BeautifulSoup(...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: In a Gitlab pipeline, if a python module is installed, why do I get a ModuleNotFoundError when I try to import it?<p>I am trying to run a python script as part of...
<p>Installing mysql itself is not enough.</p> <p>Python would need <a href="https://dev.mysql.com/doc/connector-python/en/" rel="nofollow noreferrer">mysql-connector</a> as well, as seen in <a href="https://stackoverflow.com/a/66162970/6309">this answer</a>.</p> <pre><code>pip3 install mysql-connector-python </code></p...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to maintain distance between bases in pygame<p>I am facing three problems right now and i want to get there answer seprately, First question had already been ...
<p>The error is caused by the fact that you tried to get an element from <code>base</code> instead of <code>bases</code></p> <p><s><code>if base.y - base[i+1].y &lt; 20:</code></s></p> <pre class="lang-py prettyprint-override"><code>if base.y - bases[i+1].y &lt; 20: </code></pre> <hr /> <p>If you want to make sure that...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Get name and size for each hard drive partition<p>I have written code which lists me all drive letters used on my PC. How can I get the name, the total size, the ...
<p>For Python 3.3 and above, you can use the <a href="https://docs.python.org/3.6/library/shutil.html" rel="nofollow noreferrer">shutil</a> module, which has a <code>disk_usage</code> function, returning a named tuple with the amounts of total, used and free space in your hard drive.</p> <pre><code>import shutil tota...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Regex to satisfy both string conditions<p>I have hostnames that do not have the same length/convention:</p> <pre><code>tor1er1 tor1x1ms1 </code></pre> <p>For 'tor...
<p>You may find it convenient to use named capture groups for this. You can do that with the following regular expression.</p> <pre><code>r'^(?P&lt;reg&gt;[a-z]{3})(?P&lt;env&gt;\d)(?:(?P&lt;xcon&gt;[a-z]\d))?(?P&lt;type&gt;[a-z]{2})(?P&lt;nbr&gt;\d)' </code></pre> <p>For the two example strings given in the question t...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Scrapy misssed a few items randomly on each run<p>My spider is extracting the desired data successfully except that each time I run the spider it misses out a few...
<p>After reading the documentation of retry middleware I realized that this is what I was looking for, So I overwrite the retry middleware like this if a request is a product page and response does not contain the specified xpath (title of the product) send it for the retry:</p> <pre><code>from scrapy.downloadermiddlew...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Use string to get attribute value python<p>I have this :</p> <pre><code>class A: def __getattr__(self, name): if name == 'a' return 'thi...
<p><code>__getattr__</code> is called if <code>A().a</code> doesn't exist. You still need to use <code>getattr</code> if the attribute itself is a variable.</p> <pre><code>def use_a(self, attribute='a'): a = getattr(A(), attribute) return a </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Add more descriptive labelling to x-axis of Matplotlib histogram in Python<p>I have created a histogram in a Jupyter notebook to show the distribution of time on ...
<p>When you set <code>bins=25</code>, 25 equally spaced bins are set between the lowest and highest values encountered. If you use these ranges to mark the bins, things can be confusing due to the arbitrary values. It seems more adequate to round these bin boundaries, for example to multiples of 20. Then, these values ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to make condition for Explicit Waits?<p>I'd like to create a condition for the element.</p> <p>For example, if an element is missing, a timeout error occurs. ...
<p>Did a timeout error occurs raise when initialization <code>element</code> ?,so condition depend on that.</p> <pre><code>try: element = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, &quot;CLASS NAME&quot;))) items = select_getPage_1(driver) except e: items = select_getPage...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pygame sprites overlapping issue<p>i'm learning python by myself, and started with a simple game with pygame. The game consists, so far, in a ball that's been cha...
<blockquote> <p>[...] then measures the distance between them, if the distance is less than the ball radius, it is moved away. It seems to work most of the time, but sometimes a ball overlaps. [...]</p> </blockquote> <p>Of course.You only consider 2 balls when moving a ball away. This means that if you move a ball away...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Is there a way to keep rows with a specific condition, and remove others if this condition is not met?<p>I have the following dataframe (df)</p> <pre><code> ...
<p>Use <code>groupby</code> on <code>end</code> column transformed with the minimum value of <code>Diff</code> , then compare with <code>df['Diff']</code> and keep those which return True, check how transform returns the minimum over an entire group below:</p> <pre><code>df[df['Diff'].eq(df.groupby('end')['Diff'].tran...